如何检查无效的指针? [英] How do you check for an invalid pointer?

查看:133
本文介绍了如何检查无效的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的当前代码的效果:

if( objectPointer != NULL){
    delete objectPointer;
}

不工作,因为指针被设置为无效的十六进制数编译器如:

doesn't work because the pointers are getting set to invalid hex numbers by the compiler such as:


  • 0xbaadf00d

  • 0xdeadbeef

等....

那么,在尝试删除对象之前检查无效指针的最好方法是什么?

So what's the best way to check for an invalid pointer before trying to delete the object?

推荐答案

始终将指针初始化为NULL(即0)。从 http://www.lysator.liu.se/c/c-faq/c -1.html

Always initialize your pointers to NULL (that is, 0). From http://www.lysator.liu.se/c/c-faq/c-1.html:


空指针在概念上与未初始化的指针不同。已知空指针不指向任何对象;未初始化的指针可能指向任何位置。

A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere.

这篇关于如何检查无效的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆