Koen Koen - 2 months ago 7
C Question

c: freeing an mallocated object error

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?

Answer
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.