This question already has answers here:
how 'free' works when pointer is incremented
                                
                                    (9个答案)
                                
                        
                                2年前关闭。
            
                    
我有一个全局的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

最佳答案

由于ExtractPath不返回从malloc返回的值,因此无法释放返回的字符串。准确地将您从free获得的值传递给malloc是合法的。

一旦执行temp=strchr(temp,ch);,将从malloc返回的原始值丢失。对从free返回的值调用strchr是不合法的。

这是修复它的一种方法:

char* ExtractPath(char*str)
{
    char* temp=(char*)malloc(sizeof(char)*(strlen(str))+1);
    char* orig = temp; /* save the value we got back from malloc */
    char* ret;
    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,"/");
    }
    ret = malloc (strlen(temp) + 1);
    strcpy(ret, temp); /* make a new copy to return */
    free(orig); /* pass what malloc returned to free */
    return ret; /* caller can free this since we got it back from malloc */
}

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

10-11 22:09
查看更多