Returning a pointer to an automatic variable

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.

Leave a Comment