Thursday, 15 July 2010

c++ - scope of local variables of a function in C -


I have heard about the following scenario when I started programming in C.

" The result of local variables is the error (or the value of the garbage), while trying to reach out. Since the stack turns off when returned from the function "

But the code below my sample value is 50. I am compiling the code with the latest GCC compiler.

  #include & lt; Stdio.h & gt; Int * left (); Int main () {int * p = left (); Printf ("% d \ n", * p); Return 0; } Int * left () {int i = 50; Return & amp; I; }  

Please highlight me on this issue.

Can I know behaviors in C ++ ?? It is similar to C. ..

The second code to print and you will see a different value from the first time compile it with the optimization and you will see another group of values ​​ do anything with the value and you are moving in the undefined area, which means The compiler is free to call the monsters through your nose.

On my system, call me 50 and then 0 ; With optimization, I see 0 and then 32767 .

If you create a local variable static , you can return it to the address since it gets globally (but remember that there is only one example in it is).

When a function returns, the local storage used on this stack is now considered "unused" program, since this stack does not go as high. Generally, however, the values ​​are still there, because there is no urgent need to clean them. Memory is still owned by the program, because at some point there is no point in returning some of the operating system to memory. Therefore, for your specific example, the memory in which you have compiled it has still been honored 50 officially, the value of * p Uncertainty , and an attempt to use it in undefined behavior.

There is an existential crisis of C language that on one side, it does not say anything about the various bits of stack and hexadecimal sludge which make the process of walking; On the other hand, it is necessary to understand those people to save themselves from crash, buffer overflow and undefined behavior. Just remember that you are lucky that the GCC warns about this.


No comments:

Post a Comment