Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

c++ - Using C-string gives Warning: "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 now 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 this warning:

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

And my program does not seem to work properly (might be because of the above mentioned warning).

What does the warning imply? and will it cause any problems?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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 malloc, calloc, and friends) and pass the ownership to the caller function, which will have to deallocate this space when not needed anymore (using free).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...