Invalid read size in strcasestr

痴心易碎 提交于 2019-12-11 05:46:35

问题


The following code:

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

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

gives the following error in 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)

Has anyone else seen this? This happens with & without optimizations, using gcc 4.6.1.


回答1:


If this is only happening in valgrind, it's not an error. It would be undefined behavior for your code to read beyond the end of an object obtained by malloc, but strcasestr is part of "the implementation" and thus can use implementation-specific knowledge: in this case, the fact that over-reading is perfectly safe as long as you don't cross a page boundary.



来源:https://stackoverflow.com/questions/9088933/invalid-read-size-in-strcasestr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!