Reputation: 863
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 ?
Upvotes: 0
Views: 179
Reputation: 212
you are changing memory address pointed str pointer after malloc in fun. you should do strcpy instead of direct assignment :
#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);
strcpy(*str,"HELLO");//*str = "HELLO";
printf("str = %p\n",str);
printf("&str = %p\n",&str);
printf("String str = %s\n",*str);
}
Upvotes: 0
Reputation: 4788
To answer the question of how to do this without explicit string copying, instead of
char *p = "hello";
do
char p[] = "hello";
The first points p to a non-modifiable portion of memory. The second allocates an array large enough to hold the literal and copies the literal into it.
Upvotes: 0
Reputation: 140168
you're overwriting the pointer value in the line after, making *str
point to a literal.
So you have a memory leak and undefined behaviour by trying to free
a literal.
You probably mean
strcpy(*str,"hello");
Note that those 2 lines could be changed into a working single line like this:
*str = strdup("HELLO");
which has the advantage of allocating the exact number of bytes for the string instead of guessing.
Upvotes: 6
Reputation: 70929
When you do *str = "HELLO";
it does not have the effect you expect. Instead of assigning value to the allocated memory, you are re-assigning the pointer to point to the string literal and thus later you try to deallocate it (thus the error). Instead of this you should use strcpy
like strcpy(*str, "HELLO")
.
Upvotes: 1