调用 recv() 会导致分段错误

calling recv() results in a segmentation fault

本文关键字:分段 错误 recv 调用      更新时间:2023-10-16

我正在我的Linux机器上制作一个带有tcp连接的聊天程序。我有一个工作程序将文本发送到服务器并接收数据,但是当我与 recv() 使用完全相同的行时,我遇到了分段错误。代码是这样的:

#include <stdio.h>
#include <string.h>     // for strlen()
#include <stdlib.h>     // for exit()
#include <sys/socket.h> // for send() and recv()
#include <unistd.h>     // for sleep(), close()
#include <iostream>
#include "Auxiliary.h"
#include "CreateTCPClientSocket.h"
#define RCVBUFSIZE 32   /* Size of receive buffer */
int main (int argc, char *argv[])
{
    int         sock;                   /* Socket descriptor */
    char *      echoString;             /* String to send to echo server */
    char *      tempString;             /* String to save the cin */
    char        echoBuffer[RCVBUFSIZE + 1]; /* Buffer for received string */
    int         echoStringLen;          /* Length of string to echo */
    int         bytesRcvd;              /* Bytes read in single recv() */
    bool end = false;
    parse_args (argc, argv);
    sock = CreateTCPClientSocket (argv_ip, argv_port);
    while (!end)
    {
        bool messageGet = false;
        std::cout << "What's your message:" << std::endl;
        while(!messageGet)
        {
            std::cin >> tempString;
            if(tempString != "")
            {
                echoString = tempString;
                messageGet = true;
            }
        }
        echoStringLen = strlen(echoString);          /* Determine input length */
        echoString[echoStringLen] = ''; 
        echoStringLen += 2;
        delaying();
        send(sock, echoString, echoStringLen, 0);
        info_s("Sent string:", echoString);
        // TODO: add code to receive & display the converted string from the server
        //       use recv()
        bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE-1, 0);
        std::cout << echoBuffer << std::endl;
    }
    delaying ();
    close (sock);
    info ("close & exit");
    exit (0);
}

你有多确定段错误在recv()

您对recv()的调用看起来不错,但是,较早的一行正在写入未分配的内存,这将导致段错误:

std::cin >> tempString;

尝试像这样声明tempString

#define INPUT_BUF_SIZE 100
char tempString[INPUT_BUF_SIZE + 1];

此外,这段代码似乎很不寻常:

echoStringLen = strlen(echoString);          /* Determine input length */
echoString[echoStringLen] = ''; 
echoStringLen += 2;

echoString 将已经以 null 结尾,否则strlen()不会返回正确的结果。由于它已经以 null 结尾,因此添加 没有任何效果,并且将长度增加 2 是错误的。您可以将这三行替换为以下内容:

echoStringLen = strlen(echoString);