使用C字符串给出警告:“与返回的局部变量相关联的堆栈存储器的地址"被警告. [英] Using C-string gives Warning: "Address of stack memory associated with local variable returned"

查看:59
本文介绍了使用C字符串给出警告:“与返回的局部变量相关联的堆栈存储器的地址"被警告.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是C程序员,所以我对C-string不太熟悉,但是现在我必须使用C库,因此这是我的代码的简化版本,以演示我的问题:

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;
}

我收到此警告:

警告-与本地变量"matches"相关联的堆栈内存地址

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?

推荐答案

变量 char * matchs [1]; 在堆栈上声明,当当前块超出限制时,它将自动释放.范围.

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

这意味着当您返回 matches 时,为 matches 保留的内存将被释放,并且指针将指向您不需要的内容.

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. matches [1] 声明为 static : static char * matchs [1]; -此会在静态空间而不是堆栈中为 matches 分配空间(如果您不恰当地使用它,因为 my_completion 函数的所有实例将共享相同的 matches 变量).

  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).

在调用程序函数中分配空间,并将其传递给 my_completion 函数: my_completion(matches):

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;
}

  • 在堆上的被调用函数中分配空间(使用 malloc calloc 和朋友),并将所有权传递给调用方函数,这将必须当不再需要时,请释放此空间(使用 free ).

  • 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).

    这篇关于使用C字符串给出警告:“与返回的局部变量相关联的堆栈存储器的地址"被警告.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆