gpt4 book ai didi

c - 当我释放分配的内存时出现 munmap_chunk() 错误

转载 作者:行者123 更新时间:2023-11-30 20:58:09 26 4
gpt4 key购买 nike

我有一个char* path这是全局的,后来我调用一个分配内存并返回它的函数,路径指向它,当我释放它时,我得到这个错误

唯一的方法是不释放指针

void free_memory() {

if(path!=NULL)
free(path);//problem

}

char* ExtractPath(char*str)
{
char*temp=(char*)malloc(sizeof(char)*(strlen(str))+1);
bzero(temp,strlen(temp));
char ch ='/';

if( checkUrl(str)==1) {
if(strncasecmp(str,"http://",7)==0)
str+=7;

if(strstr(str,"/")!=NULL)
{
strcpy(temp,str);
temp=strchr(temp,ch);
strtok(temp,"\t");
}
else
strcpy(temp,"/");
}
return temp;
}
path=ExtractPath(Users_input);//here the pointer points to the allocated memory that returned from the function the char*path is a global value

最佳答案

据我所知,问题在于

 bzero(temp,strlen(temp));

temp 的内容是不确定的,将其传递给 strlen() 将调用 undefined behaviour .

引用 C11,第 §7.22.3.4 章

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

也就是说,关于free()部分的错误,您必须提供由malloc()返回的exact指针或家人。

引用章节§7.22.3.3

[...] Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

在您的代码中,您实际上修改了存储在 temp 中的原始指针:

        temp=strchr(temp,ch);
strtok(temp,"\t");

并返回“修改后的”temp

temp 传递给 free() 将导致 undefined behaviour ,再一次。

关于c - 当我释放分配的内存时出现 munmap_chunk() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com