c - 在本地函数之外分配内存后,C 是否会自行释放内存?

标签 c http malloc free

这是基本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 释放内存。

如果你不这样做,内存就会泄漏,直到你的程序结束。之后操作系统回收内存。

关于c - 在本地函数之外分配内存后,C 是否会自行释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603228/

相关文章:

c - 在txt文件中查找字符串

c - 是否可以将一段代码作为宏参数传递?

http - 通过 http 使用执行器监控 spring boot

http - 等待来自组件角度 4 的服务调用中的 HTTP 响应

c - 适用于 gcc c11,但在 Clang 3.6 c11 上我得到 malloc() : memory corruption (fast): 0x0000000000fb8620

c - 构建节点时内存分配失败

c - 我将如何释放这些 mallocs?

java - 为静态嵌套类创建 stub 文件

c - C题中的冒泡排序

wcf - 为什么 WCF 将并发连接数限制为 5?