Valgrind报告了snprintf调用的错误

时间:2017-01-26 13:34:06

标签: c valgrind

我有一个非常简单的程序,当我运行valgrind进行堆栈溢出检测“--tool = exp-sgcheck”时,它会在snprintf调用中报告“无效读取大小为1”错误。我无法弄清楚原因。

这是示例程序。

#include<string.h>
#include<stdio.h>

int main( void)
{
    char path[128];
    char cmd[128];
    char cmd2[128];
    strcpy(cmd,"Command 1");
    strcpy(cmd2,"Command 2");

    snprintf(path, sizeof(path),"%s/%s", cmd , cmd2);
return 0;
}

Valgrind报告(valgrind -v --tool = exp-sgcheck ./test):

 58 --112952-- REDIR: 0x4eb72d0 (libc.so.6:__GI_strrchr) redirected to 0x4c2b0d0 (__GI_strrchr)
 59 ==112952== Invalid read of size 1
 60 ==112952==    at 0x4E77A94: vfprintf (in /usr/lib64/libc-2.17.so)
 61 ==112952==    by 0x4EA4078: vsnprintf (in /usr/lib64/libc-2.17.so)
 62 ==112952==    by 0x4E80CB1: snprintf (in /usr/lib64/libc-2.17.so)
 63 ==112952==    by 0x4005B1: main (test.c:13)
 64 ==112952==  Address 0xffefffc40 expected vs actual:
 65 ==112952==  Expected: stack array "cmd" of size 128 in frame 3 back from here
 66 ==112952==  Actual:   stack array "cmd2" of size 128 in frame 3 back from here
 67 ==112952==  Actual:   is 128 before Expected
 68 ==112952==
 69 --112952-- REDIR: 0x4eaf550 (libc.so.6:free) redirected to 0x4c299c6 (free)
 70 ==112952==
 71 ==112952== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
 72 ==112952==
 73 ==112952== 1 errors in context 1 of 1:

我正在使用带有-g标志的gcc(GCC)4.8.3来编译CentOS 7上的程序(gcc -g test.c -o test)。

当在堆上而不是堆栈上分配cmd和cmd2时,错误也会消失。

谢谢!

0 个答案:

没有答案