Mathwizurd.com is created by David Witten, a mathematics and computer science student at Stanford University. For more information, see the "About" page.

Types of Memory

When you save a variable in C++, you allocate memory. It turns out, however, that this memory is not all the same. There are three different types of memory.

Screen Shot 2019-09-29 at 7.17.10 PM.png

Static Memory

Static memory is reserved at compile time. This is a pre-determined amount of memory for static and global variables. It does not change, and it is deleted when the program terminates.

Automatic Memory

Automatic memory is reserved at run time. This exists on the stack, and it grows as more variables are saved there. It is then deleted once the variables leave their scope. This includes local variables. It’s important to note that the scope is a “block scope”, which is any area between two curly braces.

Dynamic Memory

Dynamic memory is also reserved at runtime. This exists on the heap, and it grows as more information is written to it. However, you have to manually deallocate memory there. This is exclusively for pointers. To allocate memory, you have to write “new” and to deallocate memory, you have to write “delete”.

New

The new keyword allocates the required memory to hold the data then calls a constructor to initialize the object in that memory.

New can return an error for a bad allocation, meaning you’re out of heap space/you’re requesting too much space.

New[]

When you allocate memory for a list, it allocates N blocks of memory and calls the default constructor on each element.