Variable char* matches[1];
is declared on the stack, and it will be automatically released when the current block goes out of 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:
-
Declare
matches[1]
asstatic
:static char* matches[1];
– this will allocate space formatches
in the static space and not on the stack (this may bite you if you
use it inappropriately, as all instances of themy_completion
function will share the samematches
variable). -
Allocate space in the caller function, and pass it to the
my_completion
function:my_completion(matches)
:char* matches[1]; matches = my_completion(matches); // ... char** ReadLineImpl::my_completion (char** matches) { matches[0] = "add"; return matches; }
-
Allocate space in the called function on the heap (using
malloc
,calloc
, and friends) and pass the ownership to the caller function, which will have to deallocate this space when not needed any more (usingfree
).