在编程中,检查无效指针通常是为了避免程序崩溃或出现未定义行为。以下是一些建议来检查无效指针:
nullptr
或 NULL
。int* ptr = nullptr;
new
或 malloc
)分配内存。int* ptr = new int;
if (ptr != nullptr) {
// 使用指针
}
std::unique_ptr
或 std::shared_ptr
)来自动管理内存。#include<memory>
std::unique_ptr<int> ptr(new int);
assert(ptr != nullptr);
try {
if (ptr == nullptr) {
throw std::runtime_error("Invalid pointer");
}
} catch (const std::runtime_error& e) {
std::cerr << e.what()<< std::endl;
}
通过遵循这些建议,可以有效地检查无效指针,从而避免程序中的错误和潜在问题。
领取专属 10元无门槛券
手把手带您无忧上云