簡體   English   中英

valgrind為什么不檢測數組中的多余元素

[英]why doesn't valgrind detect excess elements in arrays

我正在學習C,並正在學習包括使用valgrind的教程。 我仍在了解valgrind實際在做什么,並且想知道是否有人可以解釋為什么它在以下代碼中未檢測到任何錯誤:

#include <stdio.h>

int main(int argc, char *argv[])    
{
    int numbers[4] = {0,1,2,3,4};

    // first, print them out raw
    printf("numbers: %d %d %d %d %d\n",
           numbers[0], numbers[1],
           numbers[2], numbers[3],
           numbers[4]);

    return 0;
}

我確實收到編譯器錯誤:

greggery@Lubu:~/code$ make lc
cc -Wall -g    lc.c   -o lc
lc.c: In function ‘main’:
lc.c:5:2: warning: excess elements in array initializer [enabled by default]
lc.c:5:2: warning: (near initialization for ‘numbers’) [enabled by default]

但是當我對valgrind運行它時,沒有發現任何錯誤:

==2300== Memcheck, a memory error detector
==2300== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2300== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2300== Command: ./lc
==2300== 
numbers: 0 1 2 3 69156864
==2300== 
==2300== HEAP SUMMARY:
==2300==     in use at exit: 0 bytes in 0 blocks
==2300==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==2300== 
==2300== All heap blocks were freed -- no leaks are possible
==2300== 
==2300== For counts of detected and suppressed errors, rerun with: -v
==2300== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

因為我要在數組中添加一個額外的元素,所以這里沒有內存問題嗎? 我以為valgrind會發現最后一個元素有問題,因為它在數組之外。

你的array存儲在stack areaValgrind檢查在泄漏heap area.It檢查的根據所分配的內存泄漏dynamic allocation ,這樣你就不會被得到任何檢測Valgrind

如果您真的想看效果,請使用下面的代碼

int main()
{
  int *p=malloc(6);
}

並使用Valgrind檢查內存泄漏。

取自valgrind docs 這是對名為Memcheck為什么在此程序中找不到數組溢出的問題的答案

不幸的是,Memcheck不對全局數組或堆棧數組進行邊界檢查。 我們願意,但是不可能以適合Memcheck工作方式的合理方式進行。 抱歉。

但是,實驗工具SGcheck可以檢測到此類錯誤。 使用--tool = exp-sgcheck選項運行Valgrind進行嘗試,但要注意它不如Memcheck健壯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM