这是基本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是否处理自己分配的内存?在程序运行之前它是否被释放?或者是我的错误,我不能释放在前面的函数中声明的文件路径内存?

最佳答案

c中没有垃圾回收。
如果使用malloc分配内存,则应使用free取消分配。
如果不这样做,内存会一直泄漏到程序结束。之后操作系统会回收内存。

09-17 22:49