开发者

C Programming: calling free() on error?

开发者 https://www.devze.com 2022-12-23 19:41 出处:网络
This a follow up on my previous question. link here. My question is: Let\'s say I have the following code..

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;
开发者_StackOverflow社区    }
    ...

}
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.


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;


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号