C和C++中未定义,未指定和实现定义的行为有什么区别?
c c++ undefined-behavior unspecified-behavior implementation-defined-behavior
我在C++程序中为这样的边界分配值:
#include <iostream>
using namespace std;
int main()
{
int array[2];
array[0] = 1;
array[1] = 2;
array[3] = 3;
array[4] = 4;
cout << array[3] << endl;
cout << array[4] << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
程序打印3和4.应该是不可能的.我正在使用g ++ 4.3.3
这是编译和运行命令
$ g++ -W -Wall errorRange.cpp -o errorRange
$ ./errorRange
3
4
Run Code Online (Sandbox Code Playgroud)
只有在分配时才array[3000]=3000会给我一个分段错误.
如果gcc没有检查数组边界,我怎么能确定我的程序是否正确,因为它可能会导致一些严重的问题?
我用上面的代码替换了
vector<int> vint(2);
vint[0] = 0;
vint[1] = 1;
vint[2] = 2;
vint[5] = 5;
cout << vint[2] << endl;
cout …Run Code Online (Sandbox Code Playgroud) 我在玩不安全的Rust时遇到了这种奇怪的现象.我认为这段代码应该会出现分段错误,但事实并非如此.我错过了什么吗?我试图设置一个指向一个生命周期较短的变量的指针,然后取消引用它.
// function that sets a pointer to a variable with a shorter lifetime
unsafe fn what(p: &mut *const i32) {
let a = 2;
*p = &a;
//let addr = *p; // I will talk about this later
println!("inside: {}", **p);
}
fn main() {
let mut p: *const i32 = 0 as *const i32;
unsafe {
what(&mut p);
// I thought this line would make a segfault because 'a' goes out of scope at the end of the …Run Code Online (Sandbox Code Playgroud)