Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

seg fault on fread()

Status
Not open for further replies.

sarahnade

Programmer
Dec 22, 2005
49
0
0
US
I'm trying to use someone elses code for turning binary to numbers and I don't really know what fread() is. I get what it's trying to do, but according to waht I've googled, the first arg should be a char* right? It's giving me a seg fault, and not knowing what fread is, I am having a hard time fixing it. Here's the code:
Code:
int lines = 32507;
unsigned short int *prec;
int x=0;
char *file = "data_31.3125_-108.6875";
FILE *fp = fopen(file, "r");


for (x=0;x<lines/4;x++) {
if(fread(&prec[x],sizeof(unsigned short int),1,fp) != 1)
   printf("read prec[x] err rec %d %s\n", x, file);
//etc.

thanks!

don't panic, I'm mostly harmless
Sarah
 
The reason is because you haven't allocated an memory to the prec pointer. You should do add a malloc in there to get the correct amount of memory:

Code:
int lines = 32507;
unsigned short int *prec;
int x=0;
char *file = "data_31.3125_-108.6875";
prec = malloc(lines * sizeof(unsigned short int));
....

try adding that and see what happens.
 
Is this all the code?

The variable [tt]prec[/tt] is a pointer to an unsigned short int. The problem is, it hasn't been initialize with what to point to. So, when the [tt]fread()[/tt] reads your file, it's trying to put what it read outside it's own memory space. That's why the seg fault.

You need to allocate enough space for what you'r going to read and point [tt]spec[/tt] to it.
 
For some reason I was thinking the "sizeof()" arg inside the funtion call was allocating as I go... or something equally dumb. It all works now. Thanks.

don't panic, I'm mostly harmless
Sarah
 
There are benefits to the OO or 'highlevel', opaque
and "YOU don't need to know", maybe/possibly
garbage collected model, with functionality added
in everywhere.

Coding in C is going to hurt coming from there.
sizeof() doesn't even do what you might expect in
most cases.

I really love C and it's latter day emendations but
it's not the lowest of the highest for no reason.
 
Apropos, more convenient using of malloc to allocate an array:
Code:
Type* p;
p = malloc(size*sizeof(p[0])); /* or sizeof(*p) */
No need to rewrite Type designation.
The sizeof operator is a compilation-time op. It does not elaborate its argument - it defines type of argument only. So it's not an error to write, for example
Code:
Type* p = 0;
...
p = malloc(n*sizeof(*p));
Many years ago I liked the macros:
Code:
#define MakeArr(p,n) ((p)=malloc((n)*sizeof(*(p))))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top