在C中,无法释放并为char指针分配NULL

Bah*_*ali 1 c malloc segmentation-fault

在下面,我试图在使用malloc()分配的内存后释放并对char*进行NULL化.请帮我确定根本原因.

#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;
}
Run Code Online (Sandbox Code Playgroud)

-

错误是:

Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 7

当你这样做:

str2=str1;
Run Code Online (Sandbox Code Playgroud)

您没有将指向的字符串复制到指向str1的内存位置str2.你在做什么是复制价值str1,即字符串常量的地址,"hello world"并将其分配给str2,覆盖返回的值malloc.

然后,您尝试调用freestr2现在包含字符串常量的地址"hello world".这不是返回的地址malloc,因此您调用未定义的行为,在这种情况下表现为崩溃.

要复制字符串,请使用以下strcpy函数:

strcpy(str2, str1);
Run Code Online (Sandbox Code Playgroud)

这会将字符串中的字符复制str1到指向的内存位置str2.然后你可以安全地打电话free(str2).