我创建了一个服务器/客户端连接。服务器和客户端都编译正确,但是当我运行客户端,它给了我一个Segmentation Fault (core dumped)
C++套接字 - 客户端给出分段错误(linux)
我不知道我在做什么我的内存分配有问题。该程序不是悬挂或任何东西。我认为我的程序正在写入内存的只读部分,或者正在访问不可用的内存。
如果任何人都可以知道错误在哪里,我会非常感激。
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”);'永远不会分配任何指针指向的存储空间,永远不会指向任何内容,然后将数据复制到该未定义的区域。 KABOOOM! – user4581301
...和'char * buffer = new char(bufsize);'不是你想象的那样('()[]')。而你恰好有0'delete []'。 ......“我不知道我在做什么,我的记忆分配有问题。”一切。任何地方都没有正确的分配。 – deviantfan
为什么不直接写'char * ip =“127.0.0.1”;' – Barmar