Memory

Every day spent coding is different thanks to the NULL pointer.

There are three types of memory usage when using C++. They are static, stack and heap.

Static

Static memory is the ones allocated to the program when it start to store the code and the global structures that it use.

Stack

Used to store function return addresses, functions arguments and variables declared local in a functions. The stack has a limited size and if the big local variables are created or to much recursion there will be a stack overflow.

    • To Change the stack size in Visual Studio use /F option.
    • The details about who puts what on stack and when is selected by the calling conventions of functions. When calling a external functions you might need to select correct convention so the call works.

Heap

In C++ the memory from the heap is allocated with new and when it is not needed anymore it is removed with delete.

new / delete

Overloading New / Delete

It is possible to overload new and delete so custom actions is taken when you try to get memory for something.

malloc / free

calloc / realloc

Heap Memory Management

Memory Manager

Memory Pool

With a memory pool you keep a a maximum number of objects you need allocated all the time. Ex if you make a space shooter you have 100 laser bolt objects allocated in a array. When you need one you can simple get a pointer to one not in use and when the bolt is destroyed you can flag it as not in use and let it be. That way one does not have to new and delete the memory for them, something that can get expansive when the player spray the world with his laser gatling gun.

Memory Alignment

Reference

Memory Allocators: Table of Contents - 2016

Virtual memory explained - 2015

A memory allocator interface - 2015

Caches everywhere - 2015

gin - 2015

C++ STL container deficiencies

Introduction - 2011

Allocations Tracking - 2011

Memory Allocators Design - 2011

Allocators Overhead, Waste and Fragmentation - 2011

Alternatives to malloc and new

Operator New and Delete - Unnecessary Conditions - 2016

Garbage collection thoughts - 2012

Virtual Addressing 101 - 2011

Virtual Memory Tricks - 2017

What Every Programmer Should Know About Memory - 2007

Start Pre-allocating And Stop Worrying

C++ Core Guidelines: Rules for Allocating and Deallocating- 2017

Memory Management - 2014

Freelist Concept - 2015

A queue of page faults- 2014

Writing Cache-Friendly C++ - 2018

Memory layout of multi-dimensional arrays - 2015