Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in C, and its pointer

Old question, but I still have some thoughts though.

char * getarrmal(void)
{
    char *str;
    str = (char *)malloc(10);
    str[0] = 'a';
    str[1] = 'b';
    str[2] = 'c';
    str[3] = '\0';
    return str;
}

char * getarrdef(void)
{
    char *str = "hello";
    return str;
}

char * getarrfix(void)
{
    char str[10] = "world";
    return str;
}

Three functions. First two will return the string address and the string is stored in heap so that you can continue use it in, for example main() function.

In last function the str is a local variable and the returned str cannot be used.

My question is, when I return in the function which is calling the first two, should I manually free them? It is easy to believe for the malloc case it is true, but I am not sure if it is also the case for char *str = "hello".

If I use getarrdef() and not free its return value, then will I have memory leakage somehow?

like image 385
coldguy Avatar asked Oct 04 '22 07:10

coldguy


1 Answers

No, you should definitely not try to free the second one. It is not stored in the heap, rather it's a string literal, and trying to free it is undefined behaviour. From C++11 7.21.3.3 The free function:

... if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

For the first one, yes, it's good practice for the responsibility of allocated memory to pass along with the memory itself. That means if something allocates it and gives it to you, you are then responsible for freeing it.

That's the case even if you free it by passing it back to a function like: delarrmal() - by doing that, you've given that function responsibility to free it.

like image 129
paxdiablo Avatar answered Oct 10 '22 03:10

paxdiablo