strcasestr中的读取大小无效

时间:2012-02-01 00:04:58

标签: c valgrind

以下代码:

#include <stdlib.h>
#include <string.h>

int main() {
    char *s = strdup("keep-alive");
    if(strcasestr(s, "close")) {
    }
    free(s);
    return 0;
}

在Valgrind中给出以下错误:

==13183== Invalid read of size 8
==13183==    at 0x4F53F94: __strcasestr_sse42 (emmintrin.h:685)
==13183==    by 0x4005BF: main (in /home/aaron/dev/strtest)
==13183==  Address 0x51ce048 is 8 bytes inside a block of size 11 alloc'd
==13183==    at 0x4C28F9F: malloc (vg_replace_malloc.c:236)
==13183==    by 0x4EB1441: strdup (strdup.c:43)
==13183==    by 0x4005A5: main (in /home/aaron/dev/strtest)

有没有人见过这个?这种情况发生在&amp;没有优化,使用gcc 4.6.1。

1 个答案:

答案 0 :(得分:2)

如果这只发生在valgrind中,那不是错误。 您的代码读取超出malloc获取的对象末尾的未定义行为,但strcasestr是“实现”的一部分,因此可以使用实现 - 具体的知识:在这种情况下,只要你不跨越页面边界,过度阅读是绝对安全的。

相关问题