Posts tagged “C++

A Memory Management Adventure #2

Posted on August 30, 2013

Stacking up the heap In the last post, I promised to see how far we can go using only ‘the stack’ instead of ‘the heap’. I lied, slightly, as instead of using ‘the stack’, we’ll be creating our own stack allocator, separate from the automatic call-stack. Custom stack allocators may be familiar to people who’ve written embedded software for constrained systems.  This kind of allocator works by pre-acquiring a large block of memory (which you typically acquire from ‘the heap’!), and then treating it as a simple stack-of-bytes data structure. If the user requires some bytes, you increment the top of your stack by the requested amount — this is about as simple and as fast as it gets! I’ve also seen these referred…

A Memory Management Adventure #1

Posted on June 8, 2012

The beginning In basic terms, C’s memory management gives us ‘the stack‘ and ‘the heap‘; the former used automatically by variables with function-scope, and the latter provided by C’s malloc/free and C++’s new/delete. Managing memory allocated from the heap turns out to be error prone, with the possibility of memory leaks, double deletions, dangling pointers, and so on. All of these problems are caused by the fact that it’s up to the programmer to correctly match every new with one delete, with no restriction on said programmer from using unstructured/spaghetti-code in their buggy attempts to achieve this goal. On the other hand, memory allocated from the stack is extremely predictable — the point of construction and destruction of every object follows a strict structure that makes…