Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Malloc、free和segmentation故障_C_Segmentation Fault_Malloc_Free - Fatal编程技术网

Malloc、free和segmentation故障

Malloc、free和segmentation故障,c,segmentation-fault,malloc,free,C,Segmentation Fault,Malloc,Free,我不明白为什么在这段代码中,对“free”的调用会导致分段错误: #include <stdio.h> #include <string.h> #include <stdlib.h> char *char_arr_allocator(int length); int main(int argc, char* argv[0]){ char* stringa = NULL; stringa = char_arr_allocator(100)

我不明白为什么在这段代码中,对“free”的调用会导致分段错误:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *char_arr_allocator(int length);

int main(int argc, char* argv[0]){

    char* stringa =  NULL;
    stringa = char_arr_allocator(100);  
    printf("stringa address: %p\n", stringa); // same address as "arr"
    printf("stringa: %s\n",stringa);
    //free(stringa);

    return 0;
}

char *char_arr_allocator(int length) {
    char *arr;
    arr = malloc(length*sizeof(char));
    arr = "xxxxxxx";
    printf("arr address: %p\n", arr); // same address as "stringa"
    return arr;
}
#包括
#包括
#包括
char*char\u arr\u分配器(int-length);
int main(int argc,char*argv[0]){
char*stringa=NULL;
stringa=字符分配程序(100);
printf(“stringa地址:%p\n”,stringa);//与“arr”地址相同
printf(“stringa:%s\n”,stringa);
//免费(stringa);
返回0;
}
char*char\u arr\u分配器(整数长度){
char*arr;
arr=malloc(长度*sizeof(字符));
arr=“xxxxxxx”;
printf(“arr地址:%p\n”,arr);//与“stringa”相同的地址
返回arr;
}
有人能给我解释一下吗

谢谢,
Segolas

第三行
char\u arr\u allocator()
清除您的
malloc()
结果,并用数据页中的一块静态内存替换它。在这个问题上调用
free()
,就会失败


使用
str[n]cpy()
将字符串文本复制到缓冲区。

当用C编写常量字符串时,例如
“xxxxxx”
,所发生的情况是该字符串直接进入可执行文件。当您在源代码中引用它时,它将被一个指向该内存的指针替换。这样你就可以读这行了

 arr = "xxxxxxx";
arr
视为一个数字,如下所示:

 arr = 12345678;

那个号码就是地址
malloc
返回了一个不同的地址,当您为arr分配了一个新地址时,您将其丢弃。您将得到一个segfault,因为您试图释放一个直接在可执行文件中的常量字符串—您从未分配过它。

您正在将
arr
设置为
malloc()
的返回值,这是正确的。但随后您将重新指定它指向字符串常量
“xxxxxxx”
。因此,当您调用
free()
时,您要求运行时释放一个字符串常量,这会导致seg故障。

您正在使用
malloc
正确分配内存:

arr = malloc(length*sizeof(char));
然后你要这样做:

arr = "xxxxxxx";
这将导致
arr
指向字符串文本
“xxxxxxx”
的地址,泄漏
malloc
ed内存。对字符串文本的地址调用
free
,也会导致未定义的行为

如果要将字符串复制到分配的内存中,请使用以下方式:

strcpy(arr,"xxxxxxx");

你在UB部分是对的:使用任何指针值(除了
NULL
)调用
free
,而不是从
malloc
realloc
调用
free
,会产生未定义的行为。另外,看看它真的很不错。