![]() |
It is a standing joke among old time C programmers that you must be careful when writing code because C will happily let you shoot yourself in the foot. In keeping with this idea here are some things to be careful of when allocating memory for use in linked data structures. |
|
|
In the example two instances of struct simple are created an linked by setting S1->next = S2. Unfortunately when S2 is deleted you are left with S1->next still pointing at the now unallocated memory location. |
![]() |
|
|
to do garbage collection. Garbage collection means deallocating dynamic memory when it is no longer needed using the delete operator. Failure to do so, for example, by moving a pointer to a block of memory without first deallocating it, leaves allocated memory with no reference to it to delete it, i.e. garbage. |
![]() |
|
|
In spite of the fact that this seems to be a no-brainer it is very easy to do. You must carefully study an algorithm to determine if it is possible for it to set a pointer to NULL and include code to handle this possibility. |
![]() |
|
|
Many linked data types use NULL in pointers to indicate that is the end of the line of linked structures. If you fail to set this pointer to NULL is it not done automatically. Any non-NULL value, even if it is garbage, may be misinterpreted as a valid memory address. |
![]() |
|
|
When inserting and deleting items from a linked structure the algorithm must take into account all possible cases. For example, in the insert algorithm for an ordered linked list you may be inserting a new item into (1) an empty list, (2) at the head of the list, (3) somewhere in the middle of the list, or (4) at the end of the list. Failure to handle all of the possible cases can result in poionter problems. |
![]() |