The Proper Way To Deallocate A Pointer
May 9, 2012 Ted Holt
Jerry Clower used to tell a story about attending a rattlesnake roundup. He said that people from the humane society were on hand to be sure that the rattlesnakes were killed properly. Mr. Clower remarked that he didn’t know that there was an improper way to kill a rattlesnake. Pointers can be like rattlesnakes, biting you when you don’t expect it. Do you know the proper way to kill a pointer?
Use the %ALLOC function to allocate memory to a program. The system copies the address of the memory into a pointer variable.
D SomePointer s D SomeData s 256a based(SomePointer) /free SomePointer = %alloc(%size(SomeData));
Now you can store a value in the allocated memory, just as you store values in variables that you define in a program.
SomeData = 'Rufus T. Firefly';
And when you’re finished with the memory, you can tell the operating system you no longer need it.
However, if you’re not careful, you may inadvertently use the memory that no longer belongs to you, because the pointer still has the value the %ALLOC function assigned to it. The fact that the pointer still has a non-null value could cause big problems, because the system will still allow you to assign values to the based variable, even though that memory is no longer allocated to the program.
The solution is to use the N extender when you deallocate the memory.
The N extender sets the pointer to null. Now if you try to use the pointer, you will get error MCH3601 (Pointer not set for location referenced.) Using the N extender will let you use code like the following to keep your pointer operations from causing damage.
if SomePointer <> *null; . . . do whatever . . . else; . . . take care of the error . . . endif;
And that is the proper way to kill a pointer.