Reputation: 4668
I'm building some modular function and I'm not getting why I get a segmentation fault after freeing my module.
My .h file
void StringInit(String *this, char const *s)
{
this->str = strdup(s);
printf("%s\n", this->str);
}
void StringDestroy(String *this)
{
if(this == NULL || this->str == NULL)
return;
this->str = NULL;
free(this);
}
int main()
{
char *str;
String test;
str = "hello\n";
StringInit(&test, str);
StringDestroy(&test);
return(0);
}
Upvotes: 0
Views: 158
Reputation: 67070
You have to call free for this->str
, not for this
(because you allocated a new string with strdup
). Moreover set a member to NULL
doesn't free it:
if (this == NULL || this->str == NULL)
return;
free(this->str);
this->str = NULL;
Everything else in your code works as expected, you can allocate objects on stack (just remember you don't need to free them).
Upvotes: 4
Reputation: 38825
free
should be used to free pointers that have been allocated using malloc
. Your test
string has been allocated on the stack. As Alfe points out:
String* test = (String*)malloc(sizeof(String));
StringInit(test, str);
StringDestroy(test);
And as Adriano's answer points out, you've also allocated a new string with strdup
. Seems like there are a myriad of issues here!
Upvotes: 3