C++ Variable Memory Allocation-Collection of common programming errors

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(::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.