【问题标题】:clang vs gcc behavioral difference with AddressSanitizer使用 AddressSanitizer 的 clang vs gcc 行为差异
【发布时间】:2020-01-18 04:16:46
【问题描述】:

我有一个内存泄漏的示例代码。尽管 clang 正确显示了泄漏,但我无法使用 gcc 实现相同的目的。我使用的 gcc 版本是 4.8.5-39

代码:

#include <stdlib.h>
void *p;
int main() {
  p = malloc(7);
  p = 0; // The memory is leaked here.
  return 0;
}

叮当声:

clang -fsanitize=address -g memory-leak.c ; ASAN_OPTIONS=detect_leaks=1 ./a.out

=================================================================
==15543==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 7 byte(s) in 1 object(s) allocated from:
    #0 0x465289 in __interceptor_malloc (/u/optest/a.out+0x465289)
    #1 0x47b549 in main /u/optest/memory-leak.c:4
    #2 0x7f773fe14544 in __libc_start_main /usr/src/debug/glibc-2.17-c758a686/csu/../csu/libc-start.c:266

SUMMARY: AddressSanitizer: 7 byte(s) leaked in 1 allocation(s).

海合会:

gcc -fsanitize=address -g memory-leak.c ; ASAN_OPTIONS=detect_leaks=1 ./a.out

我需要使用 gcc。有人可以帮我理解为什么 gcc 的行为不像 clang 以及我应该怎么做才能让它工作。

【问题讨论】:

  • 用较不古老的 gcc 版本再试一次,它对我有用。

标签: gcc memory-leaks clang address-sanitizer


【解决方案1】:

Asan's FAQ 中的这一项是相关的:

Q: Why didn't ASan report an obviously invalid
   memory access in my code?

A1: If your errors is too obvious, compiler might have
    already optimized it out by the time Asan runs.

【讨论】:

  • 但是同一个 ASan 在与 clang 一起使用时会检测到内存泄漏
  • @VinodiniNatrajan Clang 的 Asan 的实现与 GCC 完全不同,所以不要期望它们之间 100% 匹配。一般来说,他们会检测到或多或少相同的错误,但这并不能保证,尤其是在这种对其他优化通道非常敏感的极端情况下。
【解决方案2】:

谁能帮我理解为什么 gcc 的行为不像 clang

Gcc-4.8 was released on March 22, 2013.

支持-fsanitize=leakwas sent on Nov. 15, 2013的补丁,可能不会向后移植到4.8版本中。

GCC-8.3 可以毫无问题地检测到此泄漏:

$ gcc -g -fsanitize=address memory-leak.c && ./a.out

=================================================================
==166614==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 7 byte(s) in 1 object(s) allocated from:
    #0 0x7fcaf3dc5330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x55d297afc162 in main /tmp/memory-leak.c:4
    #2 0x7fcaf394052a in __libc_start_main ../csu/libc-start.c:308

SUMMARY: AddressSanitizer: 7 byte(s) leaked in 1 allocation(s).

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 2012-08-14
    • 2016-07-04
    • 2014-07-12
    • 2019-03-26
    • 2019-06-05
    • 2021-04-18
    • 2018-02-08
    相关资源
    最近更新 更多