我正在开发一个更大的程序,memcpy 导致它崩溃。我在一个小程序中复制了这种情况,它做了同样的事情。我注意到由于某种原因这个程序运行良好
// Runs fine
#include <iostream>
int main() {
char* s1 = "TEST"; // src
char* s2; // dest
memcpy(s2, s1, strlen(s1) + 1);
std::cout << s2 << std::endl; // Should print "TEST"
return 0;
}
但是这个程序崩溃了
// Crashes
#include <iostream>
int main() {
char* s1 = "TEST"; // src
char* s2 = ""; // dest - Note the small change
memcpy(s2, s1, strlen(s1) + 1);
std::cout << s2 << std::endl; // Should print "TEST"
return 0;
}
我不确定为什么会这样。有人可以解释为什么它会崩溃吗?
谢谢!
最佳答案
memcpy
导致错误的原因是您试图将 s1
的内容复制到字符串文字指向的内存中,这是未定义的行为, 因为字符串文字是不可写的,即使是,也没有足够的空间。
您的第一个代码也是无效的,因为它使 memcpy
成为未初始化指针指向的内存 - 又是未定义的行为。
您可以通过添加对 new
的调用来修复第一段代码,如下所示:
char* s2 = new char[strlen(s1)+1];
第二段代码可以这样修改:
char s2[5] = "";
关于c++ - memcpy 导致程序因初始化目标而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27752285/