cservo

why the program give "Segmentation fault" after 1018 try


I'm writing a C code to open txt file and read two lines on it then print the value it worked for 1018 time then it gives "Segmentation fault" I've tried to flush the buffer but it don't work

while(running) {
    i = 0;
    if ((fptr = fopen("pwm.txt", "r")) == NULL) {
        printf("Error! File cannot be opened.");
        // Program exits if the file pointer returns NULL.
        exit(1);
    }
    fptr = fopen("pwm.txt","r");
    while (fgets(line,sizeof(line), fptr)){
        ppp[i]=atoi(line);
        i++;
    }
    fclose(fptr);
    printf("%d %d\n",ppp[0],ppp[1]);
    rc_servo_send_pulse_us(ch, 2000);
    rc_usleep(1000000/frequency_hz);
}

Solution

  • Actually, the file-opening is the likely culprit: On e.g. Linux there's a limit to how many files you can have open, and it typically defaults to 1024. A few files are used for other things, and your program probably uses some other file-handles elsewhere, leaving only around 1018 left over.

    So when you open the file twice, you leak the file handle from the first fopen call, and then your second fopen call will fail and give you a NULL pointer in return. And since you don't check for NULL the second time you attempt to use this NULL pointer and have a crash.

    Simple solution: Remove the second and unchecked call to fopen.