【问题标题】:calling recv() results in a segmentation fault调用 recv() 会导致分段错误
【发布时间】:2015-01-18 04:31:19
【问题描述】:

我正在我的 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] = '\0'; 
        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);
}

【问题讨论】:

标签: c++ linux sockets tcp segmentation-fault


【解决方案1】:

您对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] = '\0'; 
echoStringLen += 2;

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

echoStringLen = strlen(echoString);

【讨论】:

  • 当我用 recv() 函数注释该行时,程序运行正常,但是当我取消注释时,分段错误又回来了
  • 您是否尝试过分配内存来存储用户输入?
  • 顺便说一句,这样的错误在程序的其他地方表现出来的情况并不少见。在我的机器上编译和运行你的代码cin &gt;&gt; tempString; 的段错误,所以这绝对是个问题。
猜你喜欢
  • 2021-05-25
  • 1970-01-01
  • 2021-08-02
  • 2018-03-05
  • 2014-03-27
  • 2019-11-21
  • 2021-05-11
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多