Re: Parsing options in the same way they are passed to main

From: Jeff Rodriguez (newsgroup1_at_gurugeek.EXAMPLENOSPAM.com)
Date: 12/13/03


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



Relevant Pages

  • Re: realloc in function
    ... My note about memory leak is also very important for proper use of realloc. ... > Keep in mind that assigning realloc result to the same pointer may lead ... > Why would you read Microsoft news from anywhere other then the MS news ... > " MVPs earn their status by being nominated by peers and Microsoft ...
    (microsoft.public.vc.language)
  • Re: CList Concept
    ... pointer instead of a list of object. ... called automatically by the list class destructor. ... CObject myObject = new CObject; ... if I do it this way, will I get memory leak? ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: question on malloc(0)
    ... the pointer returned by malloc, it's a memory leak regardless ... After the malloccall, ptr presumably ... points to some small allocated chunk of memory. ...
    (comp.lang.c)
  • Re: memory leak
    ... you should 'delete' object BEFORE zeroing a pointer. ... > void CleanUp() ... > Calling EXAMPLE'S 1 CleanUp method gets rid of the memory leak. ... >> and will thus guarantee a memory leak. ...
    (microsoft.public.vc.language)
  • Re: get a line from file pointer & pointer doesnt seem to free correctly
    ... Jeff Rodriguez wrote: ... > pointer with a dynamic length. ... >> long string ... Read my lips: The apple doesn't fall far from the tree. ...
    (comp.lang.c)