【发布时间】:2011-03-11 10:01:42
【问题描述】:
我正在执行代码审查以解决一个很少发生的实时环境问题。它在调试环境中不可重现,因此唯一的调查手段是来自实时环境和代码分析的核心转储。以下是情况摘要:
核心转储:
(gdb) bt
#0 in strlen () from /lib/libc.so.6
#1 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string$base () from libstdc++.so.6
#2 in CustomStr::CustomStr()
代码在 Std::String 类之上有一个包装类,类似于:
class CustomStr: public string
{
//Some custom members here
};
This custom class has constructors:
CustomStr::CustomStr(const char *str):string(str)
{
//Some derived class inits
}
CustomStr::CustomStr(const CustomStr& str) : string(str.c_str())
{
//Some derived class inits
}
我认为这两个构造函数都有问题,如果传递一个指向 NULL 的指针,同样会传递给 String 构造函数,当它在内部调用 strlen() 来确定长度时,会发生未定义的行为(UB)。 我认为正确的实现方法是在调用字符串构造函数之前检查 NULL,例如:
CustomStr::CustomStr(const char *str)
{
if(str!= NULL)
string(str);
//Some derived class inits
}
CustomStr::CustomStr(const CustomStr& str)
{
if(str!= NULL)
string(str.c_str());
//Some derived class inits
}
我的问题是:
- 问题(我认为是)和建议的解决方案看起来是否有效?
- 字符串构造函数是否检查 NULL?我认为这应该是因为它在内部调用 strlen() 它将在 NULL 上显示 UB。
- 除了 NULL 检查之外,如何检查是否通过了有效的 const char*?(NOn NULL 终止的 const char* 等)
【问题讨论】:
标签: c++ string undefined-behavior