c++ - 这个指针赋值应该产生段错误?

标签 c++ pointers segmentation-fault

这不是应该产生段错误吗? 当我运行代码时,输​​出为 5。示例:http://ideone.com/gV2Nv

#include <iostream>
using std::cout;
using std::endl;

int* foo(int a) {
  int b = a;
  int* c = &b; 
  return c;
}

int main() {
  int* a = foo(5);
  cout << *a << endl; 
  return 0;
}

最佳答案

在函数中返回指向局部变量的指针是未定义的行为

未定义行为不保证段错误。它仅意味着任何行为都是可能的,并且程序可以以任何方式运行。

一个常见的误解是,未定义行为意味着代码应该产生段错误,事实是,在代码调用未定义行为的情况下,标准并不要求任何特定行为,因此也没有要求名称。

C++ 标准第 1.3.24 节指出:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

关于c++ - 这个指针赋值应该产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10492513/

相关文章:

c++ - 使用派生类的数据成员初始化基类

c - Linux内核分配实现中的指针计算

c - 仅基于 printf 语句的程序段错误

c - 指向指针的指针

c - 为什么这个程序会出现段错误?

linux - 如何在 Linux 中处理多个 SIGSEGV 事件?

c++ - 实现对命令行标志的支持的最可靠/可扩展的方法?

c++ - 用硬编码元素初始化 std::vector 的最简单方法是什么?

c++ - 通过重新排序优化分支

不太明白指针