我有这样的功能:
// string is a null-terminated char array. Replace all a in the string with b
void ReplaceCharInString(char *string, char a, char b)
{
// loop over the string char by char, to find all "a"s and replace them with "b"
}
我正在做防御性编程。问题是客户端的实现回复真正传递了一个字符数组。如果传入单个字符的地址,程序肯定会进入错误状态(可能会崩溃)。我该如何检查并避免这种情况? (我知道如果我传入 std::string 对象,问题当然就消失了)
最佳答案
不,你不能检查这个并且必须相信函数的用户传递一个实际正确的以 null 结尾的字符串。
这也是所有 C 标准库函数如 strcpy()
、strlen()
等的工作方式。
关于c++ - 我可以确定 char * 参数寻址了多少有效内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4058327/