简体   繁体   中英

Does C free memory itself after allocating it outside local function?

This is code fragment of basic http server

void sendFile(int socketNumber,char *filePath) {
    char *wwwFolder = "htdocs";
    int newFilePathSize = strlen("htdocs") + strlen(filePath) + 1;
    char *filePathFull = (char*) malloc(newFilePathSize); // allocating memory
    int i;
    for (i = 0; i < strlen(wwwFolder); i++)
        filePathFull[i] = wwwFolder[i];
    int j = 0;
    for ( ;i < newFilePathSize; i++)
    {
        filePathFull[i] = filePath[j++];
    }
    filePathFull[i] = '\0';

    //free(filePath); --
    /*filePath is a pointer with already allocated
    memory from previous function, however, if I try to free it
    in this function the program breaks down with this error:
    *** glibc detected *** ./HTTP: free(): invalid next size (fast): 0x09526008 *** */

    FILE *theFile = fopen(filePathFull,"r");
    printf("|"); printf(filePathFull); printf("| - FILEPATH\n");
    if (theFile == NULL)
    {
        send404(socketNumber);
        return;
    }
    else
        sendLegitFile(socketNumber,theFile,filePathFull);


    free(filePathFull); // freeing memory allocated in this
        //function seems to be okay
}

I want to ask, does C handle memory that was allocated itself? Is it freed while program is till running? Or is it my fault that I can't free filePath memory which was declared in previous function?

There is no garbage collection in c.
If you allocated memory using malloc you should deallocate using free .

If you don't do so the memory leaks untill your program ends. After which OS reclaims the memory.

In C, you can only release memory with free that was explicitly obtained with malloc (or calloc or realloc ). And free is finicky in that it needt to receive the exact same pointer value that was returned by malloc .

If memory was obtained in some other way (for example with an array on the stack, or a string-literal, or ...), it is a bug to pass a pointer to that memory to free .


To avoid problems, it is generally recommended to keep allocation and release of memory in the same function or in a pair of related functions, so you can easily verify that the memory passed to free was obtained from malloc (or its kin)

In addition to what Als said, the massively accepted convention in C for memory management is that the “person” that did the malloc is the one in charge of the free . As you did not allocate filePath you should not free it: the responsible person will do it. If you also do, it will result in a double free (and probably other woes if the caller tries to use filePath after you return).

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