Re: xmalloc string functions




<vippstar@xxxxxxxxx> wrote in message
On Jan 27, 5:42 pm, "Malcolm McLean" <regniz...@xxxxxxxxxxxxxx> wrote:

int main(void) {

FILE *fp = fopen("/dev/zero", "r"); /* assume UNIX & fopen doesn't
fail */
char *foo, *bar;
foo = dup("Hello, World"); /* assume success */
bar = getline(fp); /* obviously this will fail to allocate enough
memory, will quit and a memory leak will occur because the return
value of dup() was not freed */
free(bar); free(foo);
return 0;
}
-- snip.c --

I can think of a *lot* more reasons why I would not want my program to
terminate because an allocation failed.
These solutions are horrible, I strongly suggest that you avoid using
them in your own programs.

int main(int argc, char **argv)
{
FILE *fp;
char *line;
int i = 1;

if(argc != 2)
exit(EXIT_FAILURE);
fp = fopen(argv[1], "r");
if(!fp)
{
fprintf(stderr, "Can't open %s\n", argv[1]);
exit(EXIT_FAILURE);
}
while(line = getline(fp))
{
printf("%d: %s", i++, line);
free(line);
}
fclose(fp);
return 0;
}

There's a program to print a file, prepending the line number. See how simple it is, because we don't have to do any error processing?

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

.



Relevant Pages

  • Re: Allocating memory for struct - when?
    ... > believe it is because there's some memory leak - the debugger tells me ... instead of "char". ... how would the compiler know how much memory to ... example of a situation that flexible array members were designed for. ...
    (comp.lang.c)
  • Re: pointers and strings
    ... The only correct and defined way to print the value of a pointer to ... > char *p; ... you would be creating a memory leak because you would be throwing away ... have an appropriate newsgroups line in your header for your mail to be seen, ...
    (comp.lang.c.moderated)
  • Re: Non-paged pool memory leak in when huge number of files is created
    ... It's most likely not a memory leak. ... Usually file systems do not delete immediately at the file closing process the internal data structures which have been created for support of work with the opened files. ... char filename; ...
    (microsoft.public.win32.programmer.kernel)
  • Re: stl string and win32 API
    ... The difference between using a vector and manually allocating a char* ... is that vector will automatically free its memory when it goes ... whereas you have to remember to free the array. ... chance of introducing a memory leak. ...
    (microsoft.public.vc.stl)
  • Re: RfD: XCHAR wordset (for UTF-8 and alike)
    ... I have implemented unicode support in my forth system using the xchar ... needs to be set up for utf-8 support via thelocale. ... (dup drop swap etc do not produce code) ... and @ can then be used to put the char in a string ...
    (comp.lang.forth)