Wednesday, 11 October 2017

memory - Automatic variables in C++













Where
are automatic variables allocated in C++? On the stack or the
heap?



Also, I read in href="http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/" rel="nofollow
noreferrer">7.9 — The stack and the heap
that
all memory allocated on the stack is known at compile time. Is it
true? Does it mean that only static memory allocation happens on the
stack?




Also, please mention links,
references to a a complete explanatory text about memory allocation in
C++.



Answer




C++ does not have the concept
of a stack or heap, it is an implementation detail as far as the language is
concerned
.



That being said, every
implementation I know of uses the stack to manage the lifetime of local variables.
However, many local variables may end up living entirely within registers and never
touch the stack, and some local variables may be optimised out completely. Just because
you declare an automatic variable doesn't mean that it will be put on the
stack.



e.g.



int
main()
{

int x = rand();
int y =
2;
cout << x << y << endl;
return
0;
}


In this
code, with optimisations on, the variable y will almost
certainly be removed completely and variable x will probably be
given its own register. It's unlikely that either of those variables will ever exist on
the stack.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...