问题
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