The most likely problem is a missing declaration for malloc()
. You should add the line
#include <stdlib.h>
at the top of your code.
Without this line, the compiler may assume that malloc
returns int
. But if you're on a 64-bit platform, with 32-bit ints but 64-bit pointers, this will fail pretty badly. Your pointer variable ball
is likely to end up holding just 32 of the 64 bits which malloc
tried to return, with the other 32 scraped off. ball
will therefore be an invalid pointer, leading to the exception you saw.
Did you get any warnings? My compiler complains
warning: implicitly declaring library function 'malloc'
note: include the header <stdlib.h>
Or, you might have gotten a message like
warning: implicit declaration of function 'malloc' is invalid in C99
If you got warnings like these, please don't ignore them, and do learn what they mean: they're definitely things you care about. And if you didn't get warnings like these, you should figure out how to enable them in your compiler. (Or if that's not possible, you should strongly consider switching to a better compiler, if at all possible.) Modern C programming practice definitely considers this error to be one worth warning about. And there are lots of mistakes like this that are easy to make, that are frustrating to debug, and that a good compiler will warn you about, at least if you let it.