调用函数初始化服务器时出现段错误
void initializeServer(int *serverSocket, struct sockaddr_in *serverAddress) {
int status;
//Creating the server socket
*serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket < 0) {
printf("ERROR: Could not open socket. \n");
exit(-1);
}
//Setting the server address
memset(&serverAddress, 0, sizeof(&serverAddress)); //<- THIS
serverAddress->sin_family = AF_INET;
serverAddress->sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress->sin_port = htons((unsigned short) SERVER_PORT);
//Binding the server socket
status = bind(*serverSocket, (struct sockaddr *)serverAddress, sizeof(serverAddress));
if(status < 0) {
printf("ERROR: COULD NOT BIND SOCKET. \n");
exit(-1);
}
//Setting the server up to listen for clients
status = listen(*serverSocket, MAX_ROBOTS);
if(status < 0) {
printf("ERROR: COULD NOT LISTEN ON SOCKET.\n");
exit(-1);
}
}
此函数中某处出现段错误,而valgrind返回此错误:
使用大小为8的未初始化值
在0x1094F8:initializeServer
通过0x109624:主要
进程以信号11(SIGSEGV)的默认操作终止。 地址为0x108F10的映射区域的权限错误 在0x1094F8:initializeServer 通过0x109624:主要
堆很清楚,没有泄漏。我在main中测试了功能:
int main() {
int *socket_;
struct sockaddr_in *addr;
initializeServer(socket_, addr); // <- ERROR HAPPENS HERE IF UNCOMMENTED
printf("SERVER: Shutting down.\n");
}
真的为此感到困惑,我尝试了很多事情都没有用。 GDB,valgrind,重写。我似乎找不到错误的根源。