我有一个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)
但我无法弄清楚如何解决它。有谁能告诉我如何解决这个问题?
答案 0 :(得分:1)
这是您的代码的重要部分:
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]
。
答案 1 :(得分:0)
there are several basic problems with the server code.
here is just one that needs correction.
the server code is using the 'listen'/'accept' socket
to write to the client.
However, the accept function returns a NEW socket
That new socket is the one to use to communicate with the client.
here is an excerpt from the man page about the accept() function.
The accept() system call is used with connection-based socket types
(SOCK_STREAM, SOCK_SEQPACKET). It extracts the first connection
request on the queue of pending connections for the listening socket,
sockfd, creates a new connected socket, and returns a new file descrip‐
tor referring to that socket. The newly created socket is not in the
listening state. The original socket sockfd is unaffected by this
call.
The argument sockfd is a socket that has been created with socket(2),
bound to a local address with bind(2), and is listening for connections
after a listen(2).
关键信息是:
"creates a new connected socket, and returns a new file descrip‐
tor referring to that socket."
suggest reading the manual
for system functions that are called within your code
所以变量' recsize'实际上是一个与客户端进行通信的套接字。