C和C++中未定义,未指定和实现定义的行为有什么区别?
c c++ undefined-behavior unspecified-behavior implementation-defined-behavior
这个问题可以作为所有常见问题的参考:
当我将数据复制/扫描到未初始化指针所指向的地址时,为什么会出现神秘崩溃或"分段错误"?
例如:
char* ptr;
strcpy(ptr, "hello world"); // crash here!
Run Code Online (Sandbox Code Playgroud)
要么
char* ptr;
scanf("%s", ptr); // crash here!
Run Code Online (Sandbox Code Playgroud) 我们知道strcat()修饰了指向目标数组的指针,并将其与源字符串连接起来。目标数组应足够大以存储串联的结果。最近我发现,即使目标数组的大小不足以添加第二个字符串,对于小型程序,strcat()仍然可以按预期执行。我开始浏览stackoverflow并发现了几个 - 这个问题的答案。我想更深入地了解在下面运行此代码时硬件层中到底发生了什么?
#include<iostream>
#include<iomanip>
#include<cmath>
#include<cstring>
using namespace std;
int main(){
char p[6] = "Hello";
cout << "Length of p before = " << strlen(p) << endl;
cout << "Size of p before = " << sizeof(p) << endl;
char as[8] = "_World!";
cout << "Length of as before = " << strlen(as) << endl;
cout << "Size of as before = " << sizeof(as) << endl;
cout << strcat(p,as) << endl;
cout << …Run Code Online (Sandbox Code Playgroud)