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

时间:2014-11-20 10:38:41

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

我正在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);
}

1 个答案:

答案 0 :(得分: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] = '\0'; 
echoStringLen += 2;

echoString已经空终止,否则strlen()将无法返回正确的结果。由于它已经为空终止,因此添加\0无法实现任何效果,并且将长度增加2是错误的。你可以用这个替换这三行:

echoStringLen = strlen(echoString);