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

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

问题描述

我初学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 he 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. am, ther

在另一方面,你可以做到以下几点。

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 来代替。当收益 ING 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.

另外要注意的是,这是一个很好的做法,你曾与分配的内存块完成后,免费它从内存泄漏保存。一旦你释放内存,您将无法再次访问该块。

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.

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

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