为什么valgrind给我malloc错误?

时间:2018-10-02 02:22:17

标签: c

我是valgrind的新手,正试图弄清为什么它会向我抛出以下错误:

==9976== Invalid write of size 1

==9976==    at 0x4C32E0D: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9976==    by 0x109907: duplicate (parse.c:22)

==9976==    by 0x1099AB: parse (parse.c:84)

==9976==    by 0x108E8E: load_employees (emp.c:245)

==9976==    by 0x108B62: main (rpt.c:28)

==9976==  Address 0x522fe59 is 0 bytes after a block of size 9 alloc'd

==9976==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==9976==    by 0x1098F0: duplicate (parse.c:20)

==9976==    by 0x1099AB: parse (parse.c:84)

==9976==    by 0x108E8E: load_employees (emp.c:245)

==9976==    by 0x108B62: main (rpt.c:28)

我的功能:

static char *duplicate( const char *str ) {
    int len = sizeof( str );
    char *buf = (char *) malloc( (len + 1)* sizeof(*buf));

    strcpy( buf, str );
    return( buf );
}

parse.c第22行是“ return(buf);”

1 个答案:

答案 0 :(得分:3)

sizeof( str )在大多数现代体系结构上是4或8(在您的体系结构上,它看起来是8,因为valgrind输出指示已分配9个字节),无论它指向的字符串中有多少个字符。 sizeof会告诉您存储指针本身所需的大小,而不是指针所指向的字符串的长度。

相反,使用:

size_t len = strlen(str);

计算您所传递的NUL终止的字符串的长度。

顺便说一句,许多系统都提供strdup,它确实可以完成您的duplicate函数应做的事情。