c - TCP 代码中出现未初始化值错误

标签 c tcp

我有一个 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/

相关文章:

C - 如何将数组中的任意组合 char 或 int 连接到 int 或 char 类型的二进制字符串

c - 尝试构建一个函数来计算图像中的唯一像素

c - MQTT 连接特定接口(interface),如 eth0/wlan0

Linux:在 TCP 套接字上发送整个消息或不发送消息

c - 递归 POSIX 线程代码中的竞争条件?

c++ - 我如何从 DICOM 文件中提取信息?

c - BIO_reset是否在内部调用close(socket_fd)?或者我们是否显式关闭套接字文件描述符

python - 在 Python 中通过 TCP 套接字发送文件

tcp - 创建一个监听端口的简单 Rust 守护进程

unix - lsof 打印数字端口