Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Variable Memory Allocation

These are mostly compiler design questions. When your compiler compiles this, for example:

int * pData = new int[256];

How is the memory allocated on-the-fly? Does the compiler make a call to an OS routine that allocates memory for you or is a function compiled that allocates the memory for you?

Also, when you write something like this:

if (x == 5)
    int y;

Since the memory is not allocated at runtime, I'm assuming that the data takes up some room in the data segment of the program. Since the compiler can't really determine whether or not the int y; branch will be executed at runtime, is the memory reserved for the variable whether or not int y; is executed? And if it's reserved regardless, isn't it more memory-efficient to mem alloc any variables that are in a block that may or may not be executed?

o.o thanks

like image 430
Michael Zimmerman Avatar asked Dec 28 '22 22:12

Michael Zimmerman


1 Answers

For the first question: When the new operator is encounter by the compiler like in your example:

int * pData = new int[256];

It effectively emits code which looks like this:

int *pData = reinterpret_cast<int*>(::operator new(256 * sizeof(int)));
// the compiler may also choose to reserve extra space here or elsewhere to
// "remember" how many elements were allocated by this new[] so delete[] 
// can properly call all the destructors too!

If a constructor should be called, that is emitted as well (in this example, no constructor is called I believe).

operator new(std::size_t) is a function which is implemented by the standard library, often, but not always, it will boil down to a malloc call.

malloc will have to make a system call, to request memory from the OS. Since OS allocators usually work with larger fixed sized blocks of memory, malloc will not have make this call every time, only when it has exhausted the memory it currently has.


For the second question: For local variables, it really is up to the compiler. The standard makes no mention of a stack. However, most likely you are on a common architecture running a common OS and using a common compiler :-).

So for the common case, the compiler will typically reserve space at the beginning of the function call for all local variables by adjusting the stack accordingly or reserving registers for them if it can (a register being the preferred choice since it is much faster).

Then (in c++), when the variable is encountered, it will call the constructor. It could in theory, adjust the stack on an as needed basis, but this would be complicated to prove correct and less efficient. Typically reserving stack space is a single instruction, so doing it all at once is pretty optimal.

like image 111
Evan Teran Avatar answered Jan 15 '23 13:01

Evan Teran