簡體   English   中英

在將C分配給本地函數之外之后,C是否釋放內存本身?

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

這是基本http服務器的代碼片段

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
}

我想問一下,C處理分配給自己的內存嗎? 在程序運行之前可以釋放它嗎? 還是我無法釋放先前函數中聲明的filePath內存是我的錯?

c中沒有垃圾回收。
如果使用malloc分配了內存,則應該使用free進行free

如果不這樣做,則內存會泄漏,直到程序結束。 之后,操作系統將回收內存。

在C語言中,您只能釋放通過malloc (或callocrealloc )明確獲得的free內存。 free很挑剔,因為它不需要接收malloc返回的指針值。

如果以其他方式獲得內存(例如,使用堆棧上的數組或字符串型或...),則將指向該內存的指針傳遞給free是一個錯誤。


為避免出現問題,通常建議將內存的分配和釋放保持在相同的函數或一對相關的函數中,以便您可以輕松地驗證傳遞給free的內存是從malloc (或其親屬)獲得的

除了Als所說的以外,C語言中內存管理的公認約定是,執行malloc的“人”是負責free 由於您沒有分配filePath您不應free它:負責的人會這樣做。 如果您也這樣做,則將導致雙重釋放(如果調用者在返回后嘗試使用filePath ,則可能會造成其他麻煩)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM