Reputation: 44
Okay, so I have a method which I call. The called method returns a char*
, which is allocated inside the called method. After having assigned the returned char*
to a new char*
, I want to free this, after using it. But Xcode complains and throws an error. It says that the object I try to free is not allocated, which I do not get, since I am sure I allocate it.
Here is my code:
void print_r()
{
char *stateA = isActive(ruter_array[id]->flagg);
//print out the results etc
free(stateA); <-----The program crashes here.
}
char * isActive(unsigned char a_flag)
{
char *ret = malloc(5);
if((a_flag & 1) == 1)
{
//is active
ret = "yes";
return ret;
}
ret = "no";
return ret;
}
Its not important to understand what this does, but why is this freeing crashing?
Upvotes: 1
Views: 97
Reputation: 3492
You can even use strdup
:
char * isActive(unsigned char a_flag)
{
return strdup((a_flag & 1) == 1 ? "yes" : "no");
}
As written here the pointer is still allocated through malloc
so it can also be freed.
Upvotes: 1
Reputation: 14046
ret = "no";
That overwrites the pointer. Change to:
strcpy(ret, "no");
Same applies for the "yes"
case.
Also, as pointed out by @DavidSchwartz, for your purposes it is probably not necessary to use dynamically allocated memory. Could just return the string literals directly:
char * isActive(unsigned char a_flag)
{
if((a_flag & 1) == 1)
{
//is active
return "yes";
}
return "no";
}
And of course in that case the caller should not free
the returned value.
Upvotes: 3
Reputation: 21318
You allocate some memory and assign the first address of that memory to the pointer ret
, but "no"
and "yes"
are string literals that are stored statically in memory at compile-time. When you do ret = "no"
, you change the pointer so that it now points to the first character of the string literal "no"
. So, now you have lost access to the memory that you allocated, and you have a memory leak. But the crash is because you are trying to free memory that was not allocated by malloc()
or one of its friends.
Upvotes: 2