- 论坛徽章:
- 8
|
Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.
Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. This is especially the case if the program writes data to memory pointed by a dangling pointer, a silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find, or cause segmentation faults (*NIX) or general protection faults (Windows). If the overwritten data is bookkeeping data used by the system's memory allocator, the corruption can cause system instabilities.
Wild pointers arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same erratic behaviour as dangling pointers, though they are less likely to stay undetected.
http://en.wikipedia.org/wiki/Dangling_pointer
如上,free后继续使用的指针叫做悬挂指针;在设置到一个正确状态前就被引用的指针就是野指针。
避免以上情况的有效办法是设置状态标志,比如用NULL或0xFFFFFFFF之类东西指示失效状态;
任何指针,只要不再有效,就要在第一时间设置将其值改为失效标志;
如果存在并发,那么一定要将“指针失效-设置标志”这两个操作加锁并封装到一个原子性的接口里,并且通过编程规范或其他手段(如句柄)阻断对原始指针的直接访问,以避免外部访问到脏数据。
如果失效标志合理的话,其实是不用在每次引用前都检查。系统自然会在引用错误指针时core掉——因为这种bug必然和程序逻辑相关,所以只要设计合理,这种错误可以轻易发现并杜绝掉。
另外要注意编译器警告,起码要把“使用未初始化的数据”当作错误看(实际上是应该把所有警告当作错误的,不管这警告有多么微不足道)。
[ 本帖最后由 shan_ghost 于 2009-11-23 11:49 编辑 ] |
|