Using heap memory with malloc

For some reason malloc seems to confuse new programmers but it’s very straightforward.  I didn’t use it or even talk about it in the ebook. Memory allocation is not something you want to be doing in a game loop, running 60 times a second. All the memory that was ever used in the asteroids game was for text strings, variables and arrays and you don’t have to explicitly allocate any memory for those.

When you have a program that needs to allocate and free memory, like say a compiler or text editor then you grab a block of RAM using malloc.  You have to specify how much RAM you need and you must type cast it, because malloc return a void *.

Here’s an example. The image shows the output in the Visual Studio debugger.


#include <stdio.h>
#include <stdlib.h>

char* ptr[10];
int main() {
	for (int i = 0; i < 10; i++) {
		ptr[i] = (char *)malloc(1000);			
		char* aptr = ptr[i];
		for (int j = 0; j < 1000; j++) {
			aptr[j] = i + 64;
		}
        }
	for (int i = 0; i < 10; i++) {
		free(ptr[i]);
	}
}

DEbugger showing array valuesThis is what the Visual Studio debugger shows just before the final loop that calls free.

It has allocated 1000 bytes of memory for each of the ten char * in ptr[] and then fills it with 1000 each of the ASCII values 64..73 @

Finally, it frees up the memory using free. For every malloc, there should be a corresponding free or else your program will develop a memory leak.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *