1. Type Safety with Pointers
Avoid using a generic pointer type (any/void pointers) if the code isn't designed specifically for it. Example:
Code: Select all
sub putImage(img as any ptr) '' should be: img as fb.Image ptr
dim as fb.Image ptr fbImg = cast(fb.Image ptr, img) '' not safe
put (0, 0), fbImg, pset
screenres 640, 480, 32
dim as fb.Image ptr myImage = imageCreate(640, 480)
imageDestroy(myImage) '' free up memory space
Also note that we imageDestroy(myImage). Resource management can be confusing, but just know that any memory you allocate (or "reserve" for use by your program) should be deallocated (or "freed" for use by other programs). Always check the manual when creating resources to see how to properly manage them.
2. Null your pointers:
Even though the Operating System will free memory once your program has terminated, while it is still running resources continue to occupy space. Just as dangerous are resources which are allocated, freed, but not zero'd out (made into a null pointer):
Code: Select all
dim as integer ptr integerList = new integer
for i as integer = 0 to 999: integerList[i] = rnd()*1000: next
integerList = 0 '' necessary if delete doesn't automatically 0 integerList
if( integerList <> 0 ) then
'' if integerList wasn't set to 0, but the memory was freed, this program ideally crashes immediately, but often doesn't.
for i as integer = 0 to 999: print integerList[i]: next
Pointers are simply integers which "point" to a location in memory (usually RAM). Allocated pointers never equal 0, so we use 0 to indicate "null", or empty pointers. Forgetting to 0 out pointers can lead to thinking memory has been allocated when it hasn't.
Unfortunately, our ideal case of programs crashing immediately upon faulty access does not always occur. Misuse of pointers can cause unpredictable, difficult to trace bugs in code, when the OS doesn't even know you're accessing data you shouldn't be, giving you no indication of faulty memory access.