c - Reading a binary file into structure variable giving seg fault -
i have below sample file read binary structure , print length of string stored in structure. segmentation fault core dumped when try print full string. not find reason it.
#include <stdio.h> #include <stdlib.h> struct sample { unsigned int m; unsigned int v; unsigned int s[128]; int t_length; char *t; }; int main() { int i=0; unsigned int t_len=0; file *fp; struct sample sam; fp =fopen("sample.bin", "rb"); if (fp==null) { printf("file not created\n"); return -1; } fread(&sam, sizeof(sam), 1, fp); printf("t_length %d\n", sam.t_length); t_len=sam.t_length; sam.t=(char *)malloc(sizeof(char) * t_len); fseek(fp,0,seek_set); fread(&sam, sizeof(sam)+t_len, 1, fp); printf("t_length %d\n", t_len); printf("%s\n", sam.t); fclose(fp); free(sam.t); return 0; }
consider following lines:
fread(&sam, sizeof(sam), 1, fp); // ... sam.t=(char *)malloc(sizeof(char) * t_len); // ... fread(&sam, sizeof(sam)+t_len, 1, fp);
you read structure. assign t
member. read structure again, overwriting t
member.
this lead t
member no longer pointing memory allocated, , lead undefined behavior when dereference pointer.
i suggest research flexible array members might solve problem. of course requires program writing file changed use flexible array member.
if can't modify program writing file, don't re-read structure. read structure once, allocate memory, read only data put in memory allocated. skip seek, file should @ correct position anyway.
in code like
fread(&sam, sizeof sam , 1, fp); sam.t = malloc(samr.t_length); fread(sam.t, sam.t_length, 1, fp);
Comments
Post a Comment