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]);
}
}
This 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.
It’s a macro that checks an expression, and if that expression isn’t true (.e. non-zero) it outputs a message and halts the program.
The screenshot is of an open source command line editor for Dos, Windows and Linux called
Running a game at 60 frames per second means that handling things like key presses can be interesting. In the game, I call various SDL functions and via a giant switch statement set flags. Then later in the game loop, those flags are used to determine actions
In the asteroids game, when you press the s button to put up a shield, it draws a circle. I must confess, I didn’t know how to draw a cuircle so looked it up and found an example on StackOverflow. You can use code from 
The traditional way of using an include guard is to put all of the header inside a #ifdef like this.
that you can try are based on Linux but there are a few that aren’t.