Sijith
Sijith

Reputation: 3932

Memory Allocation for pointer object

How memory is allocated for pointer object

 char *str = "Check";
 char *str1 = new char[6];

Here i want to know how str is pointing to "Check" without doing memory allocation(Using new). when printing str I am getting "Check". Can some one help me the difference of both. .

Upvotes: 0

Views: 214

Answers (4)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20739

This may seams niptiking but ... many answer speak about "memory allocated by the compiler": that's not actually true: the memory is given by the OS to the process that runs the program, not by the compiler.

The compiler, in fact, stores the literals into a part of the executable file whose offset is made known to the linker, that gives those offsets to a "startup function". When the program is "lauched" the OS loads the file in memory, adds all the offsets to the load address, thus converting all offset into addresses, crates the "stack" than calls the startup function. The startup function crates the "heap", calls all the global & static object's constructors and calls main. At this point "Check" is just a sequence of bytes starting at a given address. That address is the one that is given to str.

Hence, the memory is not "allocated by the compiler". It is allocated during the program startup phase, and initialized with the data previously saved by the compiler.

Upvotes: 0

iammilind
iammilind

Reputation: 70010

First, "pointer" and "object" are different terminologies in C/C++. "pointer" is an entity which holds the address of an "object" (data type).

In the given code example, str is pointing to a memory region which is statically allocated during compilation of the code; also "Check" will remain there until the program ends.

This memory is fixed size and resides in read-only area of the code. Also that notation is deprecated in C++. It should be,

const char *str = "Check";  // "Check" is not modifiable
^^^^^ 

Upvotes: 4

unwind
unwind

Reputation: 399919

Memory for what is called "automatic" variables is not allocated from the heap (where new gets its memory from). In practice, local variables such as these are commonly on the stack. They could also be directly in CPU registers, in many cases.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613163

str is pointing to memory allocated by the compiler, typically read-only memory.

The compiler will emit Check\0 into a read-only section of the executable and then arrange that the assignment to str makes str point to that location.

Upvotes: 4

Related Questions