Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a pointer to an automatic variable

Say you have the following function:

char *getp()
{
    char s[] = "hello";
    return s;
}

Since the function is returning a pointer to a local variable in the function to be used outside, will it cause a memory leak?

P.S. I am still learning C so my question may be a bit naive...

[Update]
So, if say you want to return a new char[] array (ie maybe for a substring function), what do you return exactly? Should it be pointer to an external variable ? ie a char[] that is not local to the function?

like image 686
Andreas Grech Avatar asked Aug 03 '09 19:08

Andreas Grech


Video Answer


1 Answers

It won't cause a memory leak. It'll cause a dangling reference. The local variable is allocated on the stack and will be freed as soon as it goes out of scope. As a result, when the function ends, the pointer you are returning no longer points to a memory you own. This is not a memory leak (memory leak is when you allocate some memory and don't free it).

[Update]: To be able to return an array allocated in a function, you should allocate it outside stack (e.g. in the heap) like:

char *test() {
    char* arr = malloc(100);
    arr[0] = 'M';
    return arr;
}

Now, if you don't free the memory in the calling function after you finished using it, you'll have a memory leak.

like image 80
mmx Avatar answered Sep 20 '22 05:09

mmx