【发布时间】:2015-07-10 22:32:56
【问题描述】:
我创建了一个服务器/客户端连接。服务器和客户端都在正确编译,但是当我运行客户端时,它给了我一个Segmentation Fault (core dumped)
我不知道我的内存分配做错了什么。该程序没有悬空或任何东西。我认为我的程序正在写入内存的只读部分,或者可能正在访问不可用的内存。
如果有人能告诉我错误在哪里,我将不胜感激。
client.cpp
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int main() {
char a;
int client;
int portNum = 1500;
int bufsize = 1024;
char* buffer = new char (bufsize);
bool isExit = false;
char* ip;
strcpy(ip, "127.0.0.1");
struct sockaddr_in direc;
if ((client = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout << "Error creating socket..." << endl;
exit(0);
}
cout << "Enter # to end call" << endl;
cout << "\t\t\t[s] to begin with" << endl;
cin >> a;
cout << "Socket created successfully..." << endl;
direc.sin_family = AF_INET;
direc.sin_port = htons(portNum);
inet_pton(AF_INET, ip, &direc.sin_addr);
if (connect(client,(struct sockaddr *)&direc, sizeof(direc)) == 0)
cout << "Connection to the server " << inet_ntoa(direc.sin_addr) << endl;
cout << "Awaiting confirmation from the server..." << endl;
recv(client, buffer, bufsize, 0);
cout << "Response received: " << buffer;
cout << "\nRemember to put an asterisk at the end to send a message * \n Enter # to terminate the connection" << endl;
do {
cout << "Enter a message: ";
do {
cin >> buffer;
send(client, buffer, bufsize, 0);
if (*buffer == '#') {
send(client, buffer, bufsize, 0);
*buffer = '*';
isExit = true;
}
} while (*buffer != 42);
cout << "Mensage received: ";
do {
recv(client, buffer, bufsize, 0);
cout << buffer << " ";
if (*buffer == '#') {
*buffer = '*';
isExit = true;
}
} while (*buffer != 42);
cout << endl;
} while (!isExit);
cout << "Connection terminated. END PROGRAM\n\n";
close(client);
return 0;
}
我假设您不需要 server.cpp,因为它一切正常并正在等待传入连接。
谢谢!
【问题讨论】:
-
char* ip; strcpy(ip, "127.0.0.1");从来没有为指针分配任何存储空间,从来没有将它指向任何东西,然后将数据复制到那个未定义的区域。咔嚓! -
...而
char* buffer = new char (bufsize);与您的想法不同(() [])。而你正好有 0delete[]。 ...I don't know what I am doing wrong with my memory allocations.一切。任何地方都没有正确的分配。 -
为什么不直接写
char *ip = "127.0.0.1"; -
该缓冲区位同上。大小是已知的,所以只需
char buffer[1024]; -
cin >> buffer;如果用户输入超过 1024 个字符怎么办?send(client, buffer, bufsize, 0);只写了整个缓冲区,而不是用户输入的内容。