【发布时间】:2016-05-03 11:32:24
【问题描述】:
当 src 字符串以 \n 结尾时出现无效读取错误,删除 \n 后错误消失:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char *txt = strdup ("this is a not socket terminated message\n");
printf ("%d: %s\n", strlen (txt), txt);
free (txt);
return 0;
}
valgrind 输出:
==18929== HEAP SUMMARY:
==18929== in use at exit: 0 bytes in 0 blocks
==18929== total heap usage: 2 allocs, 2 frees, 84 bytes allocated
==18929==
==18929== All heap blocks were freed -- no leaks are possible
==18929==
==18929== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==18929==
==18929== 1 errors in context 1 of 1:
==18929== Invalid read of size 4
==18929== at 0x804847E: main (in /tmp/test)
==18929== Address 0x4204050 is 40 bytes inside a block of size 41 alloc'd
==18929== at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==18929== by 0x8048415: main (in /tmp/test)
==18929==
==18929== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
如何在不牺牲换行符的情况下解决这个问题?
【问题讨论】:
-
确定
strdup()是原型。将"%zu"用于strlen()。'\n'不太可能是问题所在。 -
在 MSVC 上没有正确的头文件的问题。他们在哪里?
-
在 MSVC 上一切皆有可能,这不是 C 的正确参考
-
问题很可能是格式说明符。使用 %lu 而不是 %d。如果您使用 gcc,请打开 -Wformat。
-
@razzak 使用 C90,将结果转换为最广泛的可用无符号类型,至少为
unsigned long:printf ("%lu\n", (unsigned long) strlen(txt));