![]() |
how would you find out if one of the pointer in a link list is corrupt or not
helo,
how would you find out one of the pointer in a link list is corrupt or not Regards, Amit |
There's no simple way. Your best bet is to put mechanisms in the linked list class (assuming you're using a class) to ensure the pointers are NULL until they are assigned. Thus, your constructor will set the list's head pointer to NULL. To check if a pointer is valid, simply compare it to NULL; if they are equal, the pointer is invalid. When you add a node, the head pointer is set to the address of the node, and the node's next pointer is set to NULL. When removing a node from the list, you'll fix the pointer for the previous node (and next node too, if it's a doubly linked list).
As long as you a) keep the pointers private, b) don't allow direct outside manipulation of them, and c) make sure your list's lifetime doesn't inadvertently exceed that of the objects it contains, you should be fine. The first two points are obvious- if code outside the class can muck with the pointers, they can become corrupted. The third point is a bit more subtle, but picture you have a linked list that will persist after objects in it might expire. This could happen if you're passing in your list to a function, allocating objects on the stack, and adding those to the list. It could also happen if you call delete for an object that exists in the list. There's no right or wrong solution. One approach is to leave the list in charge of managing object lifetime. Thus, when the list's destructor is called, it will iterate through the list, deleting each object. However, this will cause problems if other code also has a pointer to any object in the list, as those pointers will be invalidated. It also has the problems of objects in the list being invalidated before the list deletes them; this can be avoided by allocating objects off the heap (rather than stack) before adding them to the list. This isn't the most efficient solution, mind you. This is one of the areas that a garbage-collected language makes things easier. It ensures that a reference (read pointer) to an object will be valid; in other words, it makes sure not to delete the object if there are any valid references to it. This means you can add objects to a collection, and be confident that as long as the collection exists, all objects in it are valid. The price you pay, however, is non-deterministic object deletions. This means there are no guarantees how soon an object will be deleted. Once the last reference to it is gone, the garbage collector will (eventually) get around to deleting it, but this might take an arbitrarily long period of time. |
| All times are GMT -5. The time now is 11:24 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC