问题描述
我不是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;
}
我收到此警告:
我的程序似乎无法正常运行(可能是由于上述警告).
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:
-
将
matches [1]
声明为static
:static char * matchs [1];
-此会在静态空间而不是堆栈中为matches
分配空间(如果您不恰当地使用它,因为my_completion
函数的所有实例将共享相同的matches
变量).
Declare
matches[1]
asstatic
:static char* matches[1];
- thiswill allocate space formatches
in the static space and not on the stack (this may bite you if youuse it unappropriately, as all instances ofmy_completion
functionwill share the samematches
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字符串给出警告:“与返回的局部变量相关联的堆栈存储器的地址"被警告.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!