Thursday 15 March 2012

C++ Stack memory not being freed -


Please consider the following C ++ code section. I am passing a four * reference as a parameter for a forum.

  zero names (char ** str) {* str = (char *) "jUSTFORFUN"; } Int main (int argc, const char * argv []) {char * test; Name (& amp; test); The court's & lt; & Lt; testing; // Remove "JUSTFORFUN" // Delete (test); // throws error "the indication is being released is not allocated" return 0; }   

I think the memory allocated to store JUSTFORFUN in the function name (")" is allocated on the stack. Therefore, when the control goes out of the name, then the memory related to the journal (journal) should be free by the "JUSTFORFUN" compiler. My question is: When I print a test, do I still get the right output? Should not it be printed junk value?

When I do something similar to int I get the desired result.

  named zero (int ** value) {int val = 5; * Price = & amp; Val } Int main (int argc, const char * argv []) {int * val; Nameint (& amp; val); The court's & lt; & Lt; * Val; // a junk value prints 1073828160 return 0; }   

Why is the difference between the int and four * behaviors? The string on the stroke is literally "JUSTFORFUN" No

- Has static storage period in it. Despite the only visible within the function, name , the string is literally local not in that function (no string - they all have stagnant storage periods). Like

, the behavior of the first program is really well defined after the name return, with the static storage period of the word stating in the val That's what you're printing again.

In your other program, you are returning an int address that is local in functions. After returning the function, this int is no longer present, so using it gives undefined behavior - in a specific case it will probably print the value of bits currently given at that address, but its There is no guarantee what he will do.

No comments:

Post a Comment