stackoverflow上有这样一个问题,有人使用valgrind检测程序时总在sscanf上报读写越界
详情
Valgrind Invalid read of size 1 (sscanf)
Somehow Valgrind shows an error at the first lines of my program:
int main(int argc, char** argv) {
int i, r;
sscanf(argv[1], "%d", &r);
return 0;
}
Valgrind reports:
==18674== Invalid read of size 1
==18674== at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so)
==18674== by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so)
==18674== by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so)
==18674== by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so)
==18674== by 0x400DE3: main (test_b_arbre.c:18)
==18674== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==18674==
==18674==
==18674== Process terminating with default action of signal 11 (SIGSEGV)
==18674== Access not within mapped region at address 0x0
==18674== at 0x4ECB1A0: rawmemchr (in /usr/lib64/libc-2.23.so)
==18674== by 0x4EB2F41: _IO_str_init_static_internal (in /usr/lib64/libc-2.23.so)
==18674== by 0x4EA16C6: __isoc99_vsscanf (in /usr/lib64/libc-2.23.so)
==18674== by 0x4EA1666: __isoc99_sscanf (in /usr/lib64/libc-2.23.so)
==18674== by 0x400DE3: main (test_b_arbre.c:18)
原文地址:https://stackoverflow.com/questions/44641971/valgrind-invalid-read-of-size-1-sscanf
解答
原文中的问题,我直接用他的代码在本地的环境上没有重现,但曾经我遇到过这个报错。
当时是从socket中读取数据到buffer,把buffer当做第一个参数去匹配读取数据。
但是buffer中的数据肯定是不会每条就给你加一个' '的。
但sscanf匹配的时候是校验字符串结尾符' '的,因为你传入的不是标准字符串,所以sscanf就会一直往后读取去匹配。
最终,超过buffer大小后,会被valgrind判定为越界。
解决方法也很简单,直接传一个带' '的字符串就行了。闲麻烦,也可以用string(p,len)的方式转换为string,然后用string.c_str()作为第一个参数。