In C++, where are static, dynamic and local variables stored? How about in C and Java?
views:
120answers:
3If you're compiling C/C++ to create a windows executable (or maybe for any x86 system) then static and global variables are usually stored in a segment of the memory called a data segment. This memory is usually also divided to variables which are initialized and those that are not initialized by the program in their definition.
Local variables which are defined inside a functions are allocated on the running stack of the program, alongside the return value of the function.
By "dynamic" I'm assuming you mean things allocated using new
or malloc
. These are usually stored in yet another area of memory called "the heap" (which has nothing to do with the "heap" data structure)
All these details are highly platform dependent and usually, as a programmer you would not need to even be aware of them.
C, C++
- Static: Data segment of the module/dll/shared library the code is compiled into.
- Dynamic: On any memory heap, such as the C runtime heap, Win32 heap, custom heaps. Which heap the data ends up on depends on how you allocate the memory (and for C++, if operator new/delete are overridden to use a specific allocator).
- Local: On the stack frame for the current function/method.
Java
- Static: On the JVM heap.
- Dynamic: On the JVM heap.
- Local: On the stack frame for the current function/method.