我有一个 TCP 代码,但它一直在服务器代码中给出错误。
当我使用 valgrind 运行它时,我在服务器终端中收到以下内容:
==12370== Use of uninitialised value of size 8
==12370== at 0x4E6B506: ____strtol_l_internal (in /lib64/libc-2.18.so)
==12370== by 0x4E687DF: atoi (in /lib64/libc-2.18.so)
==12370== by 0x400F1D: main (in /mnt/castor/seas_home/x/xyz/TCP/serv)
==12370==
==12370== Invalid read of size 1
==12370== at 0x4E6B506: ____strtol_l_internal (in /lib64/libc-2.18.so)
==12370== by 0x4E687DF: atoi (in /lib64/libc-2.18.so)
==12370== by 0x400F1D: main (in /mnt/castor/seas_home/a/xyz/TCP/serv)
==12370== Address 0xffdfffac00000 is not stack'd, malloc'd or (recently) free'd
==12370==
==12370==
==12370== Process terminating with default action of signal 11 (SIGSEGV)
==12370== General Protection Fault
==12370== at 0x4E6B506: ____strtol_l_internal (in /lib64/libc-2.18.so)
==12370== by 0x4E687DF: atoi (in /lib64/libc-2.18.so)
==12370== by 0x400F1D: main (in /mnt/castor/seas_home/a/xyz/TCP/serv)
==12370==
==12370== HEAP SUMMARY:
==12370== in use at exit: 0 bytes in 0 blocks
==12370== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==12370==
==12370== All heap blocks were freed -- no leaks are possible
==12370==
==12370== For counts of detected and suppressed errors, rerun with: -v
==12370== Use --track-origins=yes to see where uninitialised values come from
==12370== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)
但我不知道如何解决它。谁能告诉我如何解决这个问题?
最佳答案
这是代码的重要部分:
char *words[10];
char buffer[1024];
memset(buffer, 0, sizeof buffer);
nwords = getwords(buffer, words, 10);
option = atoi(words[0]);
因为您使用空缓冲区调用 getwords
,它将返回 0 并且不会在 words
中设置任何内容,因此 words[0]
为也未初始化。
您不会检查 getwords
的返回值,但您应该检查。如果nwords==0
,则不应使用words[0]
。
关于c - TCP 代码中出现未初始化值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065387/