Re: Parsing options in the same way they are passed to main
From: Jeff Rodriguez (newsgroup1_at_gurugeek.EXAMPLENOSPAM.com)
Date: 12/13/03
- Next message: Chris Torek: "Re: Mutex in C"
- Previous message: Mac: "Re: scanf"tricks""
- In reply to: Kevin Goodsell: "Re: Parsing options in the same way they are passed to main"
- Next in thread: Kevin Goodsell: "Re: Parsing options in the same way they are passed to main"
- Reply: Kevin Goodsell: "Re: Parsing options in the same way they are passed to main"
- Reply: goose: "Re: Parsing options in the same way they are passed to main"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 13 Dec 2003 00:44:51 -0700
Kevin Goodsell wrote:
> Jeff Rodriguez wrote:
>
>> if ( (string = realloc(string, (size + strlen(argv[i])) * 2)) ==
>> NULL )
>> {
>> perror("Could not allocate memory");
>> exit(1);
>> }
>
>
> Aside from a few other errors that have already been pointed out, I
> don't think you should be calling perror without first checking the
> value of errno. I don't know off the top if my head whether realloc is
> required to set errno, but my guess is that it is not. If it doesn't,
> you may end up getting something like this:
>
> Could not allocate memory: No error
>
> Or something even more confusing, if errno has previously been set by a
> different function.
>
> This is also a guaranteed memory leak if realloc fails. The correct way
> to use realloc is to store the result into a temporary pointer, and only
> assign it to the destination pointer if it is non-null.
>
> Finally, 1 is not a portable exit code. Consider using one of the
> portable codes: 0, EXIT_SUCCESS, or EXIT_FAILURE.
>
> -Kevin
Not that I typically do the above (note how I said crude code), but how would
this be a guaranteed memory leak? If realloc fails the program exits. I'm not
sure I understand how that would cause a memory leak.
Jeff
- Next message: Chris Torek: "Re: Mutex in C"
- Previous message: Mac: "Re: scanf"tricks""
- In reply to: Kevin Goodsell: "Re: Parsing options in the same way they are passed to main"
- Next in thread: Kevin Goodsell: "Re: Parsing options in the same way they are passed to main"
- Reply: Kevin Goodsell: "Re: Parsing options in the same way they are passed to main"
- Reply: goose: "Re: Parsing options in the same way they are passed to main"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|