Friday, July 01, 2011

Heap > Stack

I wrote the following code which attempts to allocate memory for a two dimensional array of known dimensions:



As you see, I got a not-so-helpful error message. Thanks to Kenan (link only works on IE) and after some research (see links below) I found out that the stack has limited size and I should use the heap for large memory allocations. Normally, I would do that for dynamic arrays, not static arrays. So I rewrote the code and it worked:


The main disadvantages of using the heap are:
* Variables created on the heap must be manually deallocated. Variables created on the stack will go out of scope and automatically deallocate.
* Heap is slower than the stack

Links:
* What and where are the stack and heap
* local array definition versus a malloc call

No comments: