Using C-string gives Warning: “Address of stack memory associated with local variable returned”

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 staticstatic char* matches[1]; – this will allocate space for matches in the static space and not on the stack (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; }
  3. Allocate space in the called function on heap (using malloccalloc, and friends) and pass the ownership to the caller function, which will have to deallocate this space when not needed anymore (using free).

Leave a Comment