There seem to be of the order of 10 questions and (mostly) successful answers solving segmentation faults cause by misused fread()'s in C. That being said, I am having such a problem but have not found a solution.
I have a binary file containing an int
(call it nbins) and an array of float
s (of size nbins). When I try to read this file, it successfully opens and points to the file handle, but then gives a segmentation fault error when reading the nbins int
. Here is a minimal example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BPATH "/path/to/file"
int main(int agrc, char **argv)
{
FILE *fd;
int num;
char fname[500]={};
int nbins;
float *coords;
num = 5;
sprintf(fname,"%s/file%d.dat", BPATH, num);
if(!(fd=fopen(fname,"rb")))
{
printf("Can't open file: %s\n\n",fname);
exit(0);
}
printf("Reading input file:\n");
printf("%p: %s\n", fd, fname); // prints successfully
fread(&nbins, sizeof(int), 1, fd);
printf("nbins = %d", nbins); // seg faults before this print
/* EDIT: the above print isn't properly flushed without an \n
* The seg fault was not caused by the fread(), but the lack of
* the above print lead to the confusion */
coords = malloc(nbins * sizeof(float));
fread(coords, sizeof(float), nbins, fd);
fclose(fd);
free(coords);
return(0);
}
The file was created with the following formatting:
int nbins[1];
nbins[0] = 5; // this 5 is just an example...
fwrite(nbins, sizeof(int), 1, file_ptr);
fwrite(coords, sizeof(float), nbins[0], file_ptr);
I have also tried using:
int *nbins = malloc(sizeof(int));
fread(nbins, sizeof(int), 1, fd);
but this did not solve the problem.
The file does exist and is readable; I can read it just fine using Python, with NumPy's fromfile()
. Am I missing something obvious? Thanks!
perror
on failure). Compile with all warnings and debug infogcc -Wall -Wextra -g
. Use the debuggergdb
&vagrind
. – Niuseg faults here
. See new text! – Heallfread
as suggested. – Fearsomefname
is missing and depending on howfname
is declared you could get various problems. – Satiablenbins
to 0. – Niufname
? Please provide a complete example. – Hypostatizefname
in the minimal example. Should be complete, I will check if it does compile now – Heall