我在以下 C 代码中遇到分段错误:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 6667
#define MAXDATASIZE 1024
int bot_connect(char *hostname);
int bot_connect(char *hostname) {
int sockfd, numbytes, s;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char m[1024];
char *message;
char *nick = "Goo";
char *ident = "Goo";
char *realname = "Goo";
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
rv = getaddrinfo(hostname, PORT, &hints, &servinfo);
if (rv != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd == -1) {
perror("Client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("Client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "Client: failed to connect \n");
return 2;
}
freeaddrinfo(servinfo);
strcat(m, "NICK ");
strcat(m, nick);
message = m;
s = send(sockfd, message, strlen(message), 0);
strcat(m, "USER ");
strcat(m, ident);
strcat(m, " * * :");
strcat(m, realname);
message = m;
s = send(sockfd, message, strlen(message), 0);
message = "JOIN #C&T";
s = send(sockfd, message, strlen(message), 0);
close(sockfd);
}
我知道你会因为试图用内存做一些你不允许做的事情而遇到分段错误,比如改变只读内存,但据我所知,这个程序不会那样做。有没有人知道分段错误来自哪里?