【发布时间】:2015-01-03 06:16:22
【问题描述】:
我正在开发一个更大的程序,而 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;
}
我不确定为什么会这样。有人可以解释一下为什么会崩溃吗?
谢谢!
【问题讨论】:
-
如果使用 C++ 编码,您应该避免使用原始的
char*指针并使用std::string和 C++ 智能指针。
标签: c++ crash memcpy char-pointer