我写故我在

I write, therefore I am

Posts Tagged ‘Dangling Pointer’

悬挂指针(Dangling Pointer)

Posted by ieipi 于 五月 18, 2011

请看下段代码:

    int
main ( int argc, char *argv[] )
{
    unsigned int *pint = new unsigned int; 
    *pint = 5; 
    printf ( "before delete, pint = %p\n", pint );
    delete pint; 
    /*After delete the pointer, we should explicitly set it to NULL */
    /*pint = NULL; */
    printf ( "after delete, pint = %p\n", pint );

    long *plong = new long; 
    printf ( "plong = %p\n", plong );
    *plong = 10; 
    cout << "*pint = " << *pint << "; *plong = " << *plong  << endl; 
    *pint = 20; 
    cout << "*pint = " << *pint << "; *plong = " << *plong  << endl; 
    return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */

其输出为:

before delete, pint = 0x8369008
after delete, pint = 0x8369008
plong = 0x8369008
*pint = 10; *plong = 10
*pint = 20; *plong = 20

分析
delete操作只是(让操作系统)解除pint和被分配的动态内存之间的关系.但是这块内存仍在,而且,该指针仍指向这块内存.像这种指向一块已经被释放的内存的指针被称为悬挂指针(dangling pointer).使用悬挂指针容易产生难以调试的运行时错误.
为了减少这种问题,可以在释放一个指针的内存后,强制将它赋值NULL.对NULL地址的操作会立即产生段错误.

Advertisements

Posted in 语言, 技术 | Tagged: , | Leave a Comment »