C++/different variables stored where
Expert: vijayan - 8/21/2008
Questionwhere are these variables stored in memory and in which part RAM/ROM?
1)static
2)global
3)const
4)auto
Also where is segments present?in RAM or ROM
Answerwhere a variable is stored and the life time of the variable is determined my the storage duration of the variable. there are three storage durations supported by C++ : automatic, static and dynamic.
// static storage duration, modifiable
int global_var = 7 ;
// static storage duration, a constant known at compile-time
const int global_const = 9 ;
// static storage duration, constant requiring dynamic initialization
const int global_const2 = std::rand() ;
void foo( int arg )
{
// automatic storage duration, modifiable
int auto_var = 9 ;
// automatic storage duration, a constant known at compile-time
int auto_const = 9 ;
// automatic storage duration, constant, dynamic initialization
const int auto_const2 = std::rand() ;
// static storage duration, modifiable
static int static_var = 7 ;
// static storage duration, a constant known at compile-time
static const int static_const = 9 ;
// static storage duration, constant, dynamic initialization
static const int static_const2 = std::rand() ;
// int with dynamic storage duration
int* ptr = new int(100) ;
}
variables with a static storage duration are stored in the 'static data area'; an area memory (of constant size) available as part of the program right from the beginning till the end.
variables with an automatic storage duration are allocated on the 'frame' of the function (typically on the stack).
variables with a dynamic storage duration come from the 'free store'. conceptually, from the pool of 'free' memory available. typically implemented using a 'heap' to hold the memory blocks.
memory for a constant known at compile-time may be optimized away by the compiler; however its address can still be taken. and if it is stored, the virtual memory page may not be writable.
C++ does not specify anything about 'segments', 'RAM', 'ROM' etc.
however, in practice, segments are an anachronism introduced a long time ago; they are obsolete and no longer in use.
most modern hardware architectures and operating systems run a process in a 'virtual' address space. pointers that you use in your program contain virtual addresses; these are translated into physical addresses by the hardware at run-time. the same virtual address may referer to different physical (RAM etc.) addresses at different points of time. and if demand paging is used, it may not have a corrosponding physical address at all at some point of time. (the page has been paged out to disk and you get a page fault).