简体   繁体   English

打印整数时fprintf的分段错误

[英]Segmentation fault on fprintf when printing integer

I keep getting a segmentation fault on the fprintf and from all my research, my sintax and initialisations are all okay. 我一直在fprintf上遇到分段错误,从我的所有研究中,我的sintax和初始化都还可以。 Any help will be greatly appreciated. 任何帮助将不胜感激。 NOTE: The printf("enter i") are just lines i use to check where the program fails and why. 注意:printf(“ enter i”)只是我用来检查程序在哪里失败以及为什么的行。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <math.h>
#include <time.h>
#include <arpa/inet.h>
#include <stdbool.h>

void itoa(char *buf, int value);//found on stack overflow

int how_many_digits(int n)
{
int i = 0;
while(n > 10){
    n = n / 10;
    i++;
}
return i + 1;   
}

int main()
{
srand(time(NULL));
int server_port, main_socket, port;
struct sockaddr_in service; 
FILE *fileptr = NULL;
main_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
do{
    printf("enter 5\n");
    port = rand() % 62974 + 1025;
    service.sin_port = htons(port);
    if(bind(main_socket, (struct sockaddr*) &service, sizeof(service)) == 0) break;
    } while(1); 
printf("enter 4\n");    
fopen("server_port", "w");
printf("enter 6\n");
printf("%d\n", port);
fprintf(fileptr,"%d", port);
printf("enter 7\n");
fflush(fileptr);    
fclose(fileptr);
printf("enter 8\n");
listen(main_socket, 1);
server_port = accept(main_socket, NULL, NULL);
return 0;
}

Your file has not been opened correctly. 您的文件未正确打开。 You are attempting to write to a NULL pointer here: 您正在尝试在此处写入NULL指针:

fprintf(fileptr,"%d", port);

Solution: 解:

fileptr = fopen("server_port", "w");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM