在本地函数外分配内存后,C是否释放内存?
这是基本http服务器的代码片段在本地函数外分配内存后,C是否释放内存?,c,http,malloc,free,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 in
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
}
void sendFile(int socketNumber,char*filePath){
char*wwfolder=“htdocs”;
int newfilepath size=strlen(“htdocs”)+strlen(filePath)+1;
char*filePathFull=(char*)malloc(newFilePathSize);//分配内存
int i;
对于(i=0;i
我想问,C是否处理分配给自己的内存?程序运行前是否释放了它?或者是我的错,我不能释放在上一个函数中声明的文件路径内存吗?在c中没有垃圾收集。
如果使用
malloc
分配内存,则应使用free
解除分配
如果不这样做,内存将泄漏,直到程序结束。在此之后,操作系统将回收内存。在c中没有垃圾收集。
如果使用
malloc
分配内存,则应使用free
解除分配
如果不这样做,内存将泄漏,直到程序结束。在此之后,操作系统将回收内存。在C中,您只能使用
malloc
(或calloc
或realloc
)显式获得的free
释放内存。而free
非常挑剔,因为它不需要接收与malloc
返回的指针值完全相同的指针值
如果内存是以其他方式获得的(例如,使用堆栈上的数组、字符串文本或…),则将指向该内存的指针传递到free
是一个错误
为了避免出现问题,通常建议将内存分配和释放保持在同一个函数或一对相关函数中,这样您就可以轻松地验证传递给
free
的内存是从C中的malloc
(或其亲属)获得的,只能使用malloc
(或calloc
或realloc
)显式获取的free
释放内存。而free
非常挑剔,因为它不需要接收与malloc
返回的指针值完全相同的指针值
如果内存是以其他方式获得的(例如,使用堆栈上的数组、字符串文本或…),则将指向该内存的指针传递到free
是一个错误
为避免出现问题,通常建议将内存分配和释放保持在同一个函数或一对相关函数中,以便您可以轻松验证传递给
free
的内存是否来自malloc
(或其亲属)以及Als所说的内容,C语言中普遍接受的内存管理惯例是,执行malloc
的“人”负责免费
。由于您没有分配文件路径
,因此您不应该释放它:由负责人来做。如果您也这样做,它将导致双重空闲(如果调用方在您返回后尝试使用文件路径,则可能会导致其他问题)。除了Als所说的,C中广泛接受的内存管理约定是,执行malloc
的“人”负责空闲。由于您没有分配文件路径
,因此您不应该释放它:由负责人来做。如果您也这样做,则会导致双重空闲(如果调用者在返回后尝试使用filePath
,则可能会导致其他问题)。在自动存储(“堆栈上”)中更容易分配这些琐碎的缓冲区。此外,您还可以使用memcpy()或strcpy()或snprintf()要构造路径,在自动存储(“堆栈上”)中更容易分配这样的琐碎缓冲区。此外,您可以使用memcpy()或strcpy()或snprintf()来构造路径。