object - Can I end up with a pointer to an unintended location by passing a pointer to a stack variable to a function in C++? -


i know compiler optimization can result in stack frames volatility. question if safe create stack pointer in c++ , pass function , expect point same object in callee. possible end pointing unintended location because of compiler optimization.

for example safe compiler?

int main(){    std::ofstream f("somefile");    foo(&f);    return 0; } 

or should use heap consistent results.

int main(){    std::ofstream *f=new std::ofstream("somefile");      foo(f);    close(*f);    delete f;    return 0; } 

a dangling pointer created when pointer exists points object who's lifetime has ended:

std::string* s; {     std::string s1("hello");     s = &s1; } // 's' dangling pointer because 's1' has been destructed. 

this situtation not exist in either of posted code snippets, both safe. (though first preferable avoid unnecessary dynamic memory allocation).


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -