1

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)
Bahubali
  • 141
  • 1
  • 2
  • 8
  • 1
    What's the point of malloc if you then proceed to `str2=str1;`? Use `strcpy` if you want to copy strings. – cs95 Oct 22 '17 at 03:38
  • Hi, I am fiddling with strings to understand the concepts. I agree that str2=str1. This is one of the many solutions. I want to understand, why the deallocation of memory is not working in above case. Could you please help me? – Bahubali Oct 22 '17 at 03:42
  • Assigning `str2 = str1` does not copy the string pointed to by `str1` into the space pointed to by `str2`. All it does is change `str2` to point to the same thjing that `str1` points to, so they both point to the same storage. The storage returned by `malloc` is therefore lost (so it's a memory leak), and as expected the call to `free` fails. Just replace `str2=str1` with `strcpy(str2, str1)` – Tom Karzes Oct 22 '17 at 03:44
  • By the way, `* sizeof(char)` is *never* necessary since `sizeof(char)` is, by its very nature, always one. – paxdiablo Oct 22 '17 at 05:19

2 Answers2

7

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, i.e. 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).

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Alternatively, a great many systems have `strdup` for duplicating strings. Or, if they don't, you can roll your own: https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c/252802#252802 – paxdiablo Oct 22 '17 at 05:22
1

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.

John Anderson
  • 35,991
  • 4
  • 13
  • 36