【发布时间】:2017-10-22 03:36:33
【问题描述】:
在下文中,我尝试在使用 malloc() 分配的内存后释放 char * 并将其 NULLify。请帮助我找出根本原因。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
char *str1="hello world";
char *str2=malloc((strlen(str1)+1) * sizeof(char));
str2=str1;
printf("%s",str2);
free(str2);
str2=NULL;
}
--
错误是:
Segmentation fault (core dumped)
【问题讨论】:
-
如果您接着转到
str2=str1;,那么 malloc 的意义何在?如果要复制字符串,请使用strcpy。 -
嗨,我正在摆弄字符串来理解这些概念。我同意 str2=str1。这是众多解决方案之一。我想了解,为什么在上述情况下内存的释放不起作用。你能帮帮我吗?
-
赋值
str2 = str1不会将str1指向的字符串复制到str2指向的空间中。它所做的只是将str2更改为指向str1指向的相同thjing,因此它们都指向相同的存储。malloc返回的存储因此丢失(因此这是内存泄漏),并且正如预期的那样,对free的调用失败。只需将str2=str1替换为strcpy(str2, str1) -
顺便说一下,
* sizeof(char)从来没有必要,因为sizeof(char)本质上总是一个。
标签: c segmentation-fault malloc