Well, here is the thing: I don't think you really have to allocate memory on the heap at all. Besides, you are never making use of the allocated memory and it is not recommended per the pset specification page.
Let's see how you are never making use of it by looking at a relatively simpler example
int i = 10;
i = 20;
The first statement creates an int variable i
and assigns the value 10 to it. The second statement assigns the value 20 to the same variable i
. After the second statement executes, there is no way to know what was in i
before we stored the value 20 in it (unless we stored that in another variable or something of course). So we practically lost the value 10 forever because it was overwritten with the value 20.
Now let's get back to your code. When the following statement executes
char* respuesta = malloc(sizeof(char[100]));
and assuming everything works fine, the variable respuesta
of type char *
is created and the value returned by the call to malloc
(i.e., a memory address) is assigned to it.
Then comes the condition
if (strcmp(respuesta,"css")==0)
{
respuesta = "text/css";
return respuesta;
}
which obviously assigns the string "text/css" to the variable respuesta
in its body. Strings like "text/css" are often referred to as string literals. These are typically stored on a data segment on memory and NOT on the heap.
So basically, as you might have noticed, the memory address that was stored in respuesta
which was an address of an allocated location on the heap got overwritten by another memory address for another location that is not on the heap and that's exactly why free
yells at you.
Also notice that after the statement respuesta = "text/css";
got executed, you lost the memory address for the location that was allocated on the heap forever (just like we lost the 10 forever earlier), so there is actually no way you can free it.
To fix that, you may return a string literal directly!