khajvah khajvah - 3 months ago 47
C++ Question

Using C-string: "Address of stack memory associated with local variable returned"

I am not a C programmer, so I am not that familiar with C-string but new I have to use a C library so here is a shortened version of my code to demonstrate my problem:

char** ReadLineImpl::my_completion () {

char* matches[1];


matches[0] = "add";

return matches;

}


I am getting a warning:

Warning - address of stack memory associated with local variable 'matches' returned


And my application does not seem to work properly (might be because of this warning).

What is the warning and will it cause any problems?

Thanks in advance

Answer

Variable char* matches[1]; is declared on stack, and it will be automatically released when current block goes out of the scope.

This means when you return matches, memory reserved for matches will be freed, and your pointer will point to something that you don't want to.

You can solve this in many ways, and some of them are:

  1. Declare matches[1] as static: static char* matches[1]; - this will allocate space for matches on heap (this may bite you if you use it unappropriately, as all instances of my_completion function will share the same matches variable).

  2. Allocate space in the caller function and pass it to my_completion function: my_completion(matches):

    char* matches[1];
    matches = my_completion(matches);
    
    // ...
    
    char** ReadLineImpl::my_completion (char** matches) {
         matches[0] = "add";
    
         return matches;
    }
    
Comments