【问题标题】:valgrind doesn't recognize invalid writevalgrind 无法识别无效写入
【发布时间】:2019-02-04 05:11:22
【问题描述】:

Valgring 不检测内存错误。

我在 ubuntu 下使用 valgrind 3.11、gcc 5.4.0 和 在我的程序中有一个不正确的代码,就像在示例中一样。

我使用 valgrind 分析了这个程序。但是 valgrind 不会报告任何错误。

  #include <string.h>
   int main(){
     int a[3];
     memcpy(a,"aaabbbcccdddeeefffggghhh", 24);
     return 0;
   }

valgrind 有什么问题?

【问题讨论】:

  • 也许你有 8 个字节 ints
  • 在这个示例程序中增加了第三个参数 valgrind 报告了关于堆栈崩溃的信息。但在我的大应用程序中它没有帮助。我有memcpy(a,"aaaaaaabbbbbbbbbbbbbccccccccccccccddddddeeeeeffffffggggggvvvvvbbbbbbbsdddddd", 40); valgrind 仍然无法工作
  • 上次我检查时,valgrind 没有检测到大多数堆栈问题。如果您使用的是最近的 gcc/clang,您可以将 -fsanitize=address 添加到您的标志中。
  • 没有-fsanitize=address valgrind 可能不会检测到任何东西,因为所有写入都可能是有效的。而且这段代码可以优化成no-op。
  • 如果我们假设,正如 john 所建议的,sizeof(int) 确实是 8,那么就不会报告内存错误。

标签: c++ ubuntu-16.04 valgrind


【解决方案1】:

valgrind 不知道 a,也不知道它的大小,当你留在堆栈中时它无法检测到错误


比较,有那个:

#include <string.h>
int main(){
  int * a = new int[3];
  memcpy(a,"aaabbbcccdddeeefffggghhh", 24);
  return 0;
}

valgrind 可以检测到错误,因为它知道分配块的大小:

pi@raspberrypi:/tmp $ valgrind ./a.out
==16164== Memcheck, a memory error detector
==16164== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16164== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==16164== Command: ./a.out
==16164== 
==16164== Invalid write of size 8
==16164==    at 0x4865F44: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem.so)
==16164==  Address 0x4bc9f60 is 8 bytes inside a block of size 12 alloc'd
==16164==    at 0x48485F0: operator new[](unsigned int) (vg_replace_malloc.c:417)
==16164==    by 0x105A7: main (v.cc:3)
==16164== 
==16164== Invalid write of size 8
==16164==    at 0x4865F54: ??? (in /usr/lib/arm-linux-gnueabihf/libarmmem.so)
==16164==  Address 0x4bc9f68 is 4 bytes after a block of size 12 alloc'd
==16164==    at 0x48485F0: operator new[](unsigned int) (vg_replace_malloc.c:417)
==16164==    by 0x105A7: main (v.cc:3)
==16164== 
==16164== 
==16164== HEAP SUMMARY:
==16164==     in use at exit: 12 bytes in 1 blocks
==16164==   total heap usage: 2 allocs, 1 frees, 20,236 bytes allocated
==16164== 
==16164== LEAK SUMMARY:
==16164==    definitely lost: 12 bytes in 1 blocks
==16164==    indirectly lost: 0 bytes in 0 blocks
==16164==      possibly lost: 0 bytes in 0 blocks
==16164==    still reachable: 0 bytes in 0 blocks
==16164==         suppressed: 0 bytes in 0 blocks
==16164== Rerun with --leak-check=full to see details of leaked memory
==16164== 
==16164== For counts of detected and suppressed errors, rerun with: -v
==16164== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 6 from 3)

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 1970-01-01
    • 2016-08-30
    • 2016-02-11
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多