[英]segmentation fault when free() is used
This code causes a Segmentation Fault: 此代码导致分段错误:
int main(){
char *p;
char a[50] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
p = (char *)malloc(50*sizeof(char));
if(!p){
cout << "Allocation Failure";
cout << "\n";
}
else{
cout << "Allocation Success";
cout << "\n";
p = a;
cout << p;
cout << "\n";
free(p);
}
return 0;
}
The output after executing this program is: 执行该程序后的输出是:
Allocation Success
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Segmentation fault
I am not able to find the bug. 我无法找到错误。 What may be reason? 可能是什么原因?
This: 这个:
p = a;
copies the pointer , not the contents of the pointed-to memory. 复制指针 ,而不是指向内存的内容。 p
now points at the first element of the array a
. p
现在指向数组a
的第一个元素。 So when you do free(p)
, you're trying to free a non-dynamic array, which doesn't make any sense. 因此,当你执行free(p)
,你试图释放一个非动态数组,这没有任何意义。 1 1
You should investigate strncpy()
to copy strings. 您应该调查strncpy()
来复制字符串。
You're calling free
on a block of memory that wasn't allocated using one of the malloc
methods. 你在一块没有使用malloc
方法分配的内存块上调用free
。
When you do: p = a
you're assigning to p
the memory used by the stack array a
. 当你这样做: p = a
你分配给p
由堆叠阵列使用的内存a
。 That memory wasn't allocated using malloc
and hence it can't be freed using free
. 该内存未使用malloc
分配,因此无法使用free
释放。
Furthermore with that re-assignment, you'll lose track of the block that you originally allocated with malloc
and assigned to p
, causing a memory leak. 此外,通过重新分配,您将无法跟踪最初使用malloc
分配并分配给p
,从而导致内存泄漏。
char a[50]
allocates an array of fifty characters on the stack. char a[50]
在堆栈上分配一个包含50个字符的数组。 a
therefore points at an address on the stack. a
因此指向堆栈上的地址。
p = a
sets p to point at the same address as a . p = a
将p设置为与a相同的地址。 Therefore after p = a
, p points at an address on the stack. 因此,在p = a
,p指向堆栈上的地址。 Remember, p contains an address . 请记住, p包含一个地址 。
Afterwards, free(p)
tries to free a region of memory on the stack, which is illegal. 之后, free(p)
尝试释放堆栈上的内存区域,这是非法的。 You can only free memory you got from malloc(). 你只能释放你从malloc()获得的内存。
you actually meant memcpy(p,a,50); 你实际上是指memcpy(p,a,50); not p=a, remember C does not have a string data type. 不是p = a,记住C没有字符串数据类型。
p = a; // p points a
Executing this line, p should be pointing to const string ( char *
). 执行这一行,p应该指向const string( char *
)。 You cannot free()
anything that is not obtained by calling malloc
or calloc
. 你不能free()
通过调用malloc
或calloc
无法获得的任何东西。 Since in this example you try to free()
a const string, you get an error. 因为在这个例子中你试图free()
一个const字符串,你会得到一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.