Pointer resistance

If * get_ii () returned the heap memory and not the memory stack, would this problem be fixed?

01 int *get_ii()  
02 {  
03    int ii;        // Local stack variable  
04    ii = 2;  
05    return ⅈ  
06 }  
07 main()  
08 {  
09   int *ii;  
10   ii = get_ii();  // After this call the stack is given up by the routine   
11                   // get_ii() and its values are no longer safe.  
12    
13   ... Do stuff  
14   ..  ii may be corrupt by this point.  
15 }  

Source - http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html

thank

+3
source share
6 answers

Yes. Allocation from the heap will work here. Make sure that somewhere you release it, otherwise you will be a memory leak.

Often smart pointers help with this “don't forget” logic.

+7
source

- ( malloc, ) get_ii(). , . declare ii static int ii, get_ii() .

+3

, (ii get_ii() ). , int *ii main(), undefined.

, , . , , . , , !

+3

, , ii main, get_ii() , ii, .

, get_ii, , .

+2

:

std::string& makeString() //returns a reference
{ std::string str = "Dustin"; return str; }

main(){
std::string s = makeString();
//s is a dangling reference! makeString returns a reference to str, 
//but str is on the stack and goes out of scope, so we're keeping a reference to nothing
}

str ( makeString) makeString. , -, , .

+2

C, , . , get_ii , . .

If you write C ++ style, you must return by value or return a smart pointer or take a link and change the object through this link. Or you can use C-style and pass a pointer. Some C ++ authors prefer to skip the pointer because it makes it clear that the object is changing and the reference passage is unclear.

Now, if the object is small, as in this example, you should always pass and return it by value. It is faster and cheaper than using a pointer, and it makes coding simpler.

0
source

Source: https://habr.com/ru/post/1758978/


All Articles