简体   繁体   中英

failing to free char pointer memory c

I have a problem. I'm allocating space for a char* , but when I'm trying to free the space, my program crashes.

this is the code

fullPath = (char *) malloc(strlen(path) + strlen(fileData->d_name) + 1);
if (fullPath == NULL)
{
    handleErrors(ERR_ALOCATION_CODE);
}
sprintf(fullPath, "%s/%s", path, fileData->d_name);
//... some more code, I only use fullPath, I don't change it here
free(fullPath);

The code above failed when trying to free . I would appreciate some help.

You are not allocating space for the string terminating NUL character. So change allocation to this:

// allocate memory for 1st part, slash, 2nd part and terminating NUL char
fullPath = malloc(strlen(path) + 1 + strlen(fileData->d_name) + 1);

Note also, in C it's bad practice to cast return value of malloc , so I removed that.


It might be an improvement to use snprintf , in case you calculate the length wrong, though is might be a matter of opinion in this case. Anyway, then the code would become

// size for 1st part, slash, 2nd part and terminating NUL char
size_t bufsize = strlen(path) + 1 + strlen(fileData->d_name) + 1;
fullPath = malloc(bufsize);
//...
snprintf(fullPath, bufsize, "%s/%s", path, fileData->d_name);

Then a bug would not cause undefined behavior , but instead produce path with chars chopped of from the end. This is much nicer error situation (file not found error for example) than random crash, not to mention much easier to debug, when you can print the file name and see how it's not right.


Some explanation: In the question code, because you allocate 1 byte too little, you cause buffer overlow, which is undefined behavior , so basically anything can happen. For 1 byte buffer overflow, it'd be quite possible that nothing bad would happen, as there might be unused bytes at the end of the allocation. So in a way you got really lucky to catch this so early. You can imagine how hard it's to find a bug, when the program crashes only when string length is exact multiple of 16 and works otherwise... Fortunately there are tools for detecting stuff like this, but best defence is to be a pedantic C programmer, who strives to write good code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM