错误:函数返回局部变量的地址 [英] error: function returns address of local variable

查看:99
本文介绍了错误:函数返回局部变量的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的初学者,我自己学习.我正在创建以下功能:

I'm beginner with C and I am learning on my own. I am creating the following function:

char *foo(int x){
     if(x < 0){
        char a[1000];
        char b = "blah";
        x = x - 1;
        char *c = foo(x);
        strcpy(a, b);
        strcat(a, c);
        return a;
      }
    blah ...
}

我基本上是在尝试返回附加的字符串,但是出现以下错误:

I am basically trying to return an appended string, but I get the following error:

错误:函数返回本地变量的地址",有什么建议,如何解决?

"error: function returns address of local variable", any suggestions, how to fix this?

推荐答案

局部变量的生存期仅在定义它的块内部扩展.当控件移出定义了局部变量的块之外时,就不再分配该变量的存储空间(不保证).因此,在变量的生存期之外使用变量的内存地址将是不确定的行为.

The local variables have a lifetime which extends only inside the block in which it is defined. The moment the control goes outside the block in which the local variable is defined, the storage for the variable is no more allocated (not guaranteed). Therefore, using the memory address of the variable outside the lifetime area of the variable will be undefined behaviour.

另一方面,您可以执行以下操作.

On the other hand you can do the following.

 char *str_to_ret = malloc (sizeof (char) * required_size);
  .
  .
  .
 return str_to_ret;

并改用 str_to_ret .当 return 设置为 str_to_ret 时,将返回 malloc 分配的地址.由 malloc 分配的内存是从堆中分配的,其生命周期跨越程序的整个执行过程.因此,您可以在程序运行时随时随地从任何块访问内存位置.

And use the str_to_ret instead. And when returning str_to_ret, the address allocated by malloc will be returned. The memory allocated by malloc is allocated from the heap, which has a lifetime which spans the entire execution of the program. Therefore, you can access the memory location from any block and any time while the program is running.

还请注意,在完成分配的内存块后, free 可以保存内存块以防内存泄漏,这是一个好习惯.释放内存后,您将无法再次访问该块.

Also note that it is a good practice that after you have done with the allocated memory block, free it to save from memory leaks. Once you free the memory, you can't access that block again.

这篇关于错误:函数返回局部变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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