Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault when using fopen()

Tags:

c

fopen

I'm not sure why this is happening but I am getting a "Segmentation fault (core dumped)" from this very simple code. Any ideas as to why? I have to use a string to tell fopen() what file to open.

#include <stdio.h>
#include <string.h>

int main(void) {
    char *small = "small.ppm";
    FILE * fp;
    char word[5];
    fp = fopen(small, "r");
    fscanf(fp, "%s", word);
    printf("%s\n", word);

    return 0;
}
like image 776
Christian Lindemann Avatar asked Apr 01 '26 09:04

Christian Lindemann


1 Answers

Your code could invoke undefined behavior, replace by:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char *small = "small.ppm";
    FILE * fp = fopen(small, "r");
    if (fp == NULL) {
        perror("fopen()");
        return EXIT_FAILURE;
    }
    char word[5];
    if (fscanf(fp, "%4s", word) != 1) {
        fprintf(stderr, "Error parsing\n");
        return EXIT_FAILURE;
    }
    printf("%s\n", word);
}
like image 73
Stargateur Avatar answered Apr 03 '26 23:04

Stargateur