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

后端 未结 4 1787
你的背包
你的背包 2020-12-08 06:52

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:

<
4条回答
  •  盖世英雄少女心
    2020-12-08 07:30

    When you return the matches array, what you are returning is the address of the first element. This is stored on the stack inside my_completion. Once you return from my_completion that memory is reclaimed and will (most likely) eventually be reused for something else, overwriting the values stored in matches - and yes, that may well be why your application doesn't work - if it isn't right now, it probably will be once you have fixed some other problems, or changed it a bit, or something else, because this is not one of those little warnings that you can safely ignore.

    You can fix this in a few different ways. The most obvious is to simply use std::vector [or better yet std::vector] instead:

    std::vector ReadLineImpl::my_completion ()
    {
        std::vector strings;
        strings.push_back("add");
        return strings;
    }
    

    Edit: So, if the library requires a char ** as per the readline interface,then use this:

    char** ReadLineImpl::my_completion ()
    {
        char **matches = static_castmalloc(1 * sizeof(char *));
        matches[1] = "add";
        return matches;
    }
    

    Problem solved!

提交回复
热议问题