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

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

问题描述

我不是C程序员,所以我不太熟悉C字符串,但是我必须使用C库,因此这里是我的代码的简化版本,以演示我的问题:

I am not a C programmer, so I am not that familiar with C-string but new 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 application does not seem to work properly (might be because of this warning).

警告是什么,会引起任何问题吗?

What is the warning and will it cause any problems?

推荐答案

变量char* matches[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* matches[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;
}

  • 在堆上的被调用函数中分配空间(使用malloccalloc和朋友),并将所有权传递给调用者函数,当不再需要时,将不得不重新分配该空间(使用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字符串:“与返回的局部变量相关联的堆栈存储器的地址"被指定为C.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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