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.
精彩评论