Monday, November 16, 2009

Distinct memory areas in C++

Const data:
stores string literals and other data whose values are known at compile time
No objects of class type will be sotred in const data area
Available during entire lifetime of the program
read only
stack
Const Data
Stores string literals and other data whose values are known at compile time
No objects of class type
Available during entire lifetime of the program
read-only data?

free store
heap
free store and heap should not be two different memory areas; but heap is the data
model to implement the abstract type free-store. almost those terms are
interchangeable.

Global/Static
Storage allocated at program startup.
May not be initialized until after program has started execution.
The order of initialization of global variables across translation units is not defined.
Object access rules as are of Free Store.

What is the difference between const char *p, char * const p and const char * const p?

const char *p - This is a pointer to a constant character. You cannot change the value pointed by p, but you can change the pointer p itself.

*p = 'S' is illegal.
p = "Test" is legal.

Note - char const *p is the same.


const * char p - This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by p.

*p = 'A' is legal.
p = "Hello" is illegal.


const char * const p - This is a constant pointer to constant character. You cannot change the value pointed by p nor the pointer p.

*p = 'A' is illegal.
p = "Hello" is also illegal.