这是基本 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 内存是我的错?