0

So I have this code in which allocation is happening in one function and deallocation is being done in the calling function. Getting Segmentation fault or Abort message while trying to free the memory either by ptr or *ptr. Kindly have a look:

#include <stdio.h>

int main()
{

    char *ptr;
    fun(&ptr);
    printf("ptr = %p\n",ptr);
    printf("&ptr = %p\n",&ptr);
    printf("String ptr = %s\n",ptr);
    free (ptr);

    return 0;
}
void fun(char **str)
{
    *str = malloc(10);
    *str = "HELLO";
    printf("str = %p\n",str);
    printf("&str = %p\n",&str);

    printf("String str = %s\n",*str);
}

Following is the output:

str = 0x7ffe63247858                                                                                                                 
&str = 0x7ffe63247838                                                                                                                
String str = HELLO                                                                                                                   
ptr = 0x400764                                                                                                                       
&ptr = 0x7ffe63247858                                                                                                                
String ptr = HELLO                                                                                                                   
*** Error in `/home/a.out': munmap_chunk(): invalid pointer: 0x0000000000400764 ***                                                  
Aborted  

Question :

Why can't we free ptr ? And if we can, what is the best way to do it ?

Manoj
  • 853
  • 1
  • 7
  • 28

1 Answers1

1

The problem is that the pointer variable is passed by value. You need to emulate pass-by-value with the pointer, by passing a pointer to the pointer. Use the address-of operator & to get that.

There's also a second problem, and that's your reassignment of the pointer inside the function. You first allocate memory and make str point to that. Then you directly reassign the pointer and make it point somewhere else, losing the memory you have allocated. You need to copy the string into the allocated memory.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621