Re: xmalloc string functions
- From: "Malcolm McLean" <regniztar@xxxxxxxxxxxxxx>
- Date: Mon, 28 Jan 2008 09:21:35 -0000
<vippstar@xxxxxxxxx> wrote in message
On Jan 27, 5:42 pm, "Malcolm McLean" <regniz...@xxxxxxxxxxxxxx> wrote:
int main(void) {int main(int argc, char **argv)
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.
{
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
.
- Follow-Ups:
- Re: xmalloc string functions
- From: Flash Gordon
- Re: xmalloc string functions
- From: Ben Bacarisse
- Re: xmalloc string functions
- From: Eric Sosman
- Re: xmalloc string functions
- From: Richard Heathfield
- Re: xmalloc string functions
- References:
- xmalloc string functions
- From: Malcolm McLean
- Re: xmalloc string functions
- From: santosh
- Re: xmalloc string functions
- From: Malcolm McLean
- Re: xmalloc string functions
- From: vippstar
- xmalloc string functions
- Prev by Date: Re: xmalloc string functions
- Next by Date: Re: xmalloc string functions
- Previous by thread: Re: xmalloc string functions
- Next by thread: Re: xmalloc string functions
- Index(es):
Relevant Pages
|