tags:

views:

120

answers:

3

In C++, where are static, dynamic and local variables stored? How about in C and Java?

A: 

Start here: http://en.wikipedia.org/wiki/Data_segment

mrjoltcola
+4  A: 

If 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.

shoosh
+1 (except for as a programmer you should be aware of them)
mrjoltcola
explain please.
shoosh
Sure. Most definitely any C/C++ "programmer" worth their mettle knows where their variables are stored. It comes with the territory. For managed languages, one can argue otherwise, but not for C/C++.
mrjoltcola
I'd say it's nearly always useful to be *aware* of how the constructs you work with are implemented (see Joel Spolsky's "The Law of Leaky Abstractions" article for more discussion of this point). But for most day-to-day activities, it's probably more *useful* to think of things at the higher level of abstraction.
Daniel Pryden
I suppose there's a useful reason to know about stack variables- If you run into an unexpected stack overflow but without any infinite recursion, one place to look for are large definitions of local variables.
shoosh
You should be aware of where your data is allocated because there can be large performance differences; unless performance is irrelevant I guess.
Inverse
+1  A: 

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.
Stephen Kellett