简体   繁体   中英

In C, Unable to free and assign NULL to char pointer

In the following, I am trying to free and NULLify the char * after using memory allocated by malloc(). Please help me to identify the root cause.

#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;
}

--

Error is :

Segmentation fault (core dumped)

When you do this:

str2=str1;

You are not copying the string pointed to by str1 into the memory location pointed to by str2 . What you are doing is copying the value of str1 , ie the address of the string constant "hello world" and assigning it to str2 , overwriting the value returned by malloc .

You then attempt to call free on str2 which now contains the address of the string constant "hello world" . This was not an address returned by malloc , so you invoke undefined behavior , which in this case manifests as a crash.

To copy a string, use the strcpy function:

strcpy(str2, str1);

This will copy the characters in the string str1 to the memory location pointed to by str2 . Then you can safely call free(str2) .

When you do the str2 = str1, then str2 now points at the "hello world" string, not at the memory you malloced. That command does not copy the string, but just changes the location that str2 points at. You are trying to free memory that was assigned by the system (not malloc), and you have a memory leak. The memory you malloced now has no way to be accessed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM