Corrupt pointer in a linked list

2020-02-26 01:53发布

How would you find if one of the pointers in a linked list is corrupted or not ?

5条回答
▲ chillily
2楼-- · 2020-02-26 02:07

There are several possibilities.

If the list is doubly linked, it's possible to check the back pointer from what a front pointer points to, or vice versa.

If you have some idea as to the range of expected memory addresses, you can check. This is particularly true of the linked list is allocated from a limited number of chunks of memory, rather than having each node allocated independently.

If the nodes have some recognizable data in them, you can run down the list and check for recognizable data.

This looks to me like one of those questions where the interviewer isn't expecting a snappy answer, but rather an analysis of the question including further questions from you.

查看更多
时光不老,我们不散
3楼-- · 2020-02-26 02:14

Yuo could keep a doubly linked list. Then you can check that node->child->parent == node (although if node->child has become corrupt this has a reasonable chance of causing an exception)

查看更多
姐就是有狂的资本
4楼-- · 2020-02-26 02:20

Introduce a magic value in your node structures. Initialize it upon new node allocation. Before every access, check if the node structure that the pointer points to contains the valid magic. If the pointer points at an unreadable data block, your program will crash. For that, on Windows there's API VirtualQuery() - call that before reading, and make sure the pointer points at readable data.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-26 02:23

It's sort of a pain, but you can record the values of each pointer as you come across them with your debugger and verify that it's consistent with what you'd expect to find (if you'd expect a pointer to be NULL, make sure it's NULL. if you'd expect a pointer to refer to an already existing object, verify that that object's address has that value, etc.).

查看更多
手持菜刀,她持情操
6楼-- · 2020-02-26 02:26

Several debuggers / bound-checkers will do this for you, but a cheap and quick solution to this question is to

  • Alter the structure of the list's nodes to include one additional char[n] field (or more typically two, one as the first the other as the last fields in the structure, hence allowing bounds-checking in addition to pointer corruption).
  • Initiallize these fields with a short (but long enough...) constant string such as "VaL1D-LiST-NODE 1234" when the nodes are created.
  • Check that the values read in this(these) field(s) match the expected text, each time a node is dereferenced, and before using the node in earnest.

When the field(s)' value do not match this is either the indication that:

  • the pointer is invalid (it never pointed to a list node)
  • something else is overwriting the node structure (the pointer is "valid" but the data it points to has been corrupted).
查看更多
登录 后发表回答