简体   繁体   English

堆栈段C数组

[英]Stack Segment C Arrays

I came across an example in a page outlining the various ways to represent a string in C structures. 我在页面中遇到一个示例,概述了用C结构表示字符串的各种方法。 It explains that an array defined in a function outside main will be stored in the stack segment and as such will not necessarily be present following its return potentially causing a runtime error. 它解释说,在main外部的函数中定义的数组将存储在堆栈段中,因此在其返回后不一定会存在,可能会导致运行时错误。

HIGHLIGHTED POSSIBLE DUPLICATE EXPLAINED WHY THE ARRAY FAILED ON RETURN IE THE POINTER TO ELEMENT 0 RETURNED IS NO LONGER VALID BUT DID NOT SHOW THAT THE REASON VARIABLES OF THE SAME STORAGE CLASS (AUTO) ARE SUCCESSFUL IS THAT THEY PASS A VALUE WHICH SURVIVES THE REMOVAL OF THE STACK FRAME 高亮显示可能的重复说明为什么数组返回失败,即指针返回到0元素不是有效的,但仍未表明同一存储类别(自动)的原因变量是否成功,它们是否都说明了价值堆栈框架

" the below program may print some garbage data as string is stored in stack frame of function getString() and data may not be there after getString() returns. " “下面的程序可能会打印一些垃圾数据,因为字符串存储在函数getString()的堆栈帧中,并且在getString()返回之后数据可能不存在。”

char *getString() 
{ 
  char str[] = "GfG"; /* Stored in stack segment */

  /* Problem: string may not be present after getSting() returns */
  return str;  
}      
int main() 
{ 
  printf("%s", getString());   
  getchar(); 
  return 0; 
} 

I understand that other local C variables will also be defined in their respective stack frames and obviously they can be returned so why is it an issue for arrays? 我知道其他局部C变量也将在它们各自的堆栈框架中定义,并且显然可以将它们返回,所以为什么数组有问题?

Thanks 谢谢

This should roughly explains what happened, after return from getString(), its stack is not valid anymore. 这应该大致解释发生了什么,从getString()返回后,其堆栈不再有效。

         ^            ^ 
         |  not valid |    ^            ^
         +------------+    | not valid  |
  str--> | "GfG"      |    | not valid  | <---+
         |  ---       |    | not valid  |     |
         | stack of   |    +------------+     |
         | getString  |    | return(str)| ----+
         +------------+    | ---        |
         |            |    |            |
         | stack of   |    | stack of   |
         | main()     |    | main()     |
         +------------+    +------------+

If compiled with gcc -W -Wall (should always use those options), it should give the warning: 如果使用gcc -W -Wall编译(应始终使用这些选项),则应给出警告:

warning: function returns address of local variable [-Wreturn-local-addr]

The difference is in returning a value as opposed to returning a pointer. 区别在于返回值与返回指针不同。

When you do this: 执行此操作时:

int f()
{
    int x = 9;
    return x;
}

int main()
{
    int a = f();
    printf("a=%d\n", a);
    return;
}

This is valid because even though x is out of scope when f returns, it is the value stored in x (9 in this case) that is returned. 这是有效的,因为即使f返回时x超出范围,也将返回存储在x (在这种情况下为9)。 That value is then assigned to a and subsequently printed. 然后a值分配给a并随后打印。

In your example you're returning an array. 在您的示例中,您将返回一个数组。 In most contexts, an array used in an expression decays into a pointer to its first element. 在大多数情况下,表达式中使用的数组会衰减为指向其第一个元素的指针。 So return str is the same as return &str[0] . 因此return strreturn &str[0] That pointer value is returned and passed to printf . 该指针值将返回并传递给printf Then printf tried to dereference that pointer, but the memory it points to (the array str ) is no longer valid. 然后printf尝试取消对该指针的引用,但是它指向的内存(数组str )不再有效。

So you can return values from a function, but if that value is a pointer to a local variable it will not be valid. 因此,您可以从函数返回值,但是如果该值是指向局部变量的指针,则它将无效。

There are 2 situations: 有两种情况:

  1. When you return a simple value like an int or char from a local function and that variable is defined/declared in that local function. 当您从本地函数返回一个简单的值(如intchar ,并且该变量在该本地函数中定义/声明时。 It happens successfully, because while returning the value is actually copied . 它成功发生,因为返回值时实际上已复制

  2. Now you have string "GfG" in str and when you do return str , the value that is copied is what is there in str and that is the address location of the array. 现在你有字符串"GfG"str ,当你做return str ,被复制的价值是什么,是有在str那就是数组的地址位置。 So in this case the array location (pointer) is copied, while the contents of this array vanishes (since the contents were on local stack frame). 因此,在这种情况下,将复制数组位置(指针),而此数组的内容将消失(因为内容位于本地堆栈帧上)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM