c++ - 未定义的清理无法检测到简单的堆栈越界错误

标签 c++ indexoutofboundsexception sanitization

<分区>

#include <iostream>
void fill(int *);

int main() {
    int a[1];
    int b[1];
    a[0] = 1;
    b[0] = 2;
    fill(a);

    std::cout << *a << " " << *b << std::endl;
}

void fill (int * x) {
    x[1] = 3;
}

此代码会产生越界情况,其中堆栈值 b[0]fill(a) 覆盖。

代码已经编译使用

g++ main.cpp -fsanitize=undefined -lstdc++ -lubsan

但是 sanitizer 无法检测到错误。

我错过了什么吗?

最佳答案

Am I missing something?

是的。堆栈溢出是由地址检测器检测的,而不是 UB 检测器。使用 -fsanitize=address 编译您的代码片段可以得到

=17847==ERROR: AddressSanitizer: stack-buffer-overflow on address ... at pc ...

#0 0x10f7f5d44 in fill(int*) (a.out:x86_64+0x100000d44)
#1 0x10f7f5b81 in main (a.out:x86_64+0x100000b81)
#2 0x7fff5f490014 in start (libdyld.dylib:x86_64+0x1014)

...

从技术上讲,对堆栈的越界访问确实会导致未定义的行为。但是,将导致 UB 的所有内容都放入 UB sanitizer 中可能是关注点分离太少了。来自clang address sanitizer docs :

AddressSanitizer is a fast memory error detector. It consists of a compiler instrumentation module and a run-time library. The tool can detect the following types of bugs:

  • Out-of-bounds accesses to heap, stack and globals
  • ...

虽然可以找到 UB sanitizer 实现的检查列表 here (再次,clang 文档)。

关于c++ - 未定义的清理无法检测到简单的堆栈越界错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56002832/

相关文章:

c++ - Qt - 为什么我不能在 MainWindow 中为我的自定义按钮触发 mousePressEvent

C++ OOP 设计决策

java - 使用我的多边形填充算法填充多边形会出现越界错误

java - 从 BufferedImage 渲染 Sprite 时出现问题

java - 在解决了最初的越界异常后,如何将 a 与 b 或 c 相乘

php - 如何处理混合使用 HTML 和标点符号的用户输入?

c++ - 如何调用一个方法,该方法需要一个子类对象,子类对象由指向其父类(super class)的指针引用?

c++ - C++0x lambda 的 undefined symbol ?

php - PHP 中的数据清理

ruby - 在 Ruby 中形成卫生 shell 命令或系统调用