[英]Malloc, free and segmentation fault
I don't understand why, in this code, the call to "free" cause a segmentation fault: 我不明白为什么在这段代码中,对“ 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;
}
Can someone explain it to me? 有人可以向我解释吗?
Thanks, Segolas 谢谢,Segolas
You are allocating the memory using malloc
correctly: 您正在使用
malloc
正确分配内存:
arr = malloc(length*sizeof(char));
then you do this: 然后您可以这样做:
arr = "xxxxxxx";
this will cause arr
point to the address of the string literal "xxxxxxx"
, leaking your malloc
ed memory. 这将导致
arr
指向字符串常量的地址"xxxxxxx"
, 泄露你malloc
版内存。 And also calling free
on address of string literal leads to undefined behavior. 而且,对字符串文字的地址进行
free
调用会导致未定义的行为。
If you want to copy the string into the allocated memory use strcpy
as: 如果要将字符串复制到分配的内存中,请使用
strcpy
作为:
strcpy(arr,"xxxxxxx");
The third line of char_arr_allocator()
wipes out your malloc()
result and replaces it with a chunk of static memory in the data page. char_arr_allocator()
的第三行擦除您的malloc()
结果,并将其替换为数据页中的大量静态内存。 Calling free()
on this blows up. 在此调用
free()
炸毁。
Use str[n]cpy()
to copy the string literal to the buffer instead. 使用
str[n]cpy()
可以将字符串文字复制到缓冲区中。
When you write a constant string in C, such as "xxxxxx"
, what happens is that that string goes directly into the executable. 当您使用C编写常量字符串(例如
"xxxxxx"
,会发生该字符串直接进入可执行文件的情况。 When you refer to it in your source, it gets replaced with a pointer to that memory. 当您在源中引用它时,它将被指向该内存的指针替换。 So you can read the line
这样你就可以读线
arr = "xxxxxxx";
Treating arr
as a number as something like: 将
arr
视为数字,如下所示:
arr = 12345678;
Where that number is an address. 该号码是地址。
malloc
has returned a different address, and you threw that away when you assigned a new address to arr. malloc
返回了一个不同的地址,当您为arr分配一个新地址时,您将其丢弃。 You are getting a segfault because you are trying to free a constant string which is directly in your executable -- you never allocated it. 之所以出现段错误,是因为您试图释放直接在可执行文件中的常量字符串-您从未分配过它。
You are setting arr
to the return value of malloc()
, which is correct. 您正在将
arr
设置为malloc()
的返回值,这是正确的。 But you are then reassigning it to point at the string constant "xxxxxxx"
. 但是,然后您将其重新分配为指向字符串常量
"xxxxxxx"
。 So when you call free()
, you're asking the runtime to free a string constant, which causes the seg fault. 因此,当您调用
free()
,您要求运行时释放一个字符串常量,这会导致seg错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.