【发布时间】: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);
}
【问题讨论】:
-
bytesRcvd 应该是 ssize_t 类型。看到这个线程:stackoverflow.com/questions/19224655/using-ssize-t-vs-int
-
我改了没区别,收到还是有分段错误
标签: c++ linux sockets tcp segmentation-fault