deltaskelta deltaskelta - 3 months ago 14
C Question

C code is segfaulting while using fseek

I have a code that I thought I had compiled in the past and successfully but now I am running into a segfault and I cannot see why.

FILE *numbers = fopen("./e13.txt", "r");

//seeking the end of the file to get the correct size for the string
//I will store
fseek(numbers, 0, SEEK_END);
long fsize = ftell(numbers);
fseek(numbers, 0, SEEK_SET);

//Allocating memory to the string
char *string = malloc(fsize + 1);

I am trying to read a file into memory so I am getting the proper size of it and trying to
that amount of memory. I think it is segfaulting in the fseek function but I cannot see why...


fopen can return NULL if it cannot open the file. This is probably what is happening here. You should check it like:

if(!numbers){/*report error and exit*/}

Also, if you simply want to get the size of a file, consider using stat if your system supports it. If you also want to open it and read it all into memory, I would suggest using mmap if your system supports it:

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

int fd = open("e13.txt", O_RDONLY);
if(!fd){/*report error and exit*/}
size_t len;
    struct stat stat_buf;
    if(fstat(fd, &stat_buf)){
        /*report error and exit*/
    len = stat_buf.st_size;
void *map_addr = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
if(!map_addr){/*report error and exit*/}
/*do work*/
munmap(map_addr, len);