tags:

views:

90

answers:

3

Hi all,

This a follow up on my previous question. link here.

My question is: Let's say I have the following code..

char* buf = (char*) malloc(1024);

...
for(; i<20; i++) { 
    if(read(fd, buf, 1024)   == -1) { // read off a file and store in buffer
         perror("read failed");
         return 1;
    }
    ...

}
free(buf);

what i'm trying to get at is that - what if an error occurs at read()? does that mean my allocated memory never gets freed? If that's the case, how do I handle this? Should I be calling free() as part of error handling?

Once again, I apologize for the bad English. ^^;

Many thanks, K.

+3  A: 

Yes the memory will be leaked.

You can do it like this:

char* buf = (char*) malloc(1024);
int errcode = 0;

...
for(; i<20; i++) { 
    if(read(fd, buf, 1024)   == -1) { // read off a file and store in buffer
         perror("read failed");
         errcode = 1;
         break;  // or "goto cleanup;"
    }
    ...

}
free(buf);
return errcode;
KennyTM
Depending on operating system, the memory will be freed automatically when the process exits.
Jens Björnhager
@Jens: There's no indication OP's function is `int main()`.
KennyTM
@KennyTM: missing label `cleanup:` before the `free(buf);` call.
tomlogic
@tomlogic: There will be a `cleanup:` label if I really use `goto`.
KennyTM
+3  A: 

Unless you run on a very constrained embedded CPU with a very small stack, there is no reason to allocate that buffer from the heap. One kilobyte is peanuts. Change your declaration to this:

char buf[1024];

and you can exit your function without having to clean up.

Hans Passant
+1  A: 

It depends on whether you consider the error recoverable or not.

If you think the error may be recoverable, and your function returns an error code (or somehow signals the caller), do make sure to free memory, and any other resources (such as file descriptors) that won't be used again.

If you don't think the error is recoverable, and you exit the program (via abort or something similar), don't worry about freeing resources. The system will take care of it for you as your program exits.

Jay Conrod