这是基本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/