我在代码库中找到了这个(简化的)代码片段,这让我觉得不愉快.它既可以工作,也可以工作,或者永远不会被调用.我希望有一些缓冲区溢出,但是当我在一个在线编译器中尝试它时,它肯定不起作用,但也不会溢出.我正在查看strcat它的定义,它将从其null终止符开始将源写入目标,但我假设在这种情况下,目标缓冲区(创建为a std::string)应该太小..
#include <iostream>
#include "string.h"
using namespace std;
void addtostring(char* str){
char str2[12] = "goodbye";
strcat(str, str2);
}
int main()
{
std::string my_string = "hello";
addtostring((char*)my_string.c_str());
cout << my_string << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个操作的实际行为是什么?
Nat*_*ica 10
这个操作的实际行为是什么?
行为未定义.首先,写入任何字符c_str是未定义的行为.其次,如果你使用了data反而获得了char*,覆盖null终止符也是未定义的行为.最后,双方c_str并data只给你一个指针(p即具有元素的有效范围)[p, p + size()].写入该范围之外的任何元素也是未定义的行为.
如果要修改字符串,则需要使用字符串的成员/自由函数来执行此操作.您的功能可以重写为
void addtostring(std::string& str){
str += "goodbye";
}
Run Code Online (Sandbox Code Playgroud)
这将有明确定义的行为.