I have a below sample file where I read the binary into structure and print the length of the string which is stored in structure. But I get a segmentation fault core dumped when I try to print the full string. I could not find the reason for 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 is %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 is %d\n", t_len);
printf("%s\n", sam.t);
fclose(fp);
free(sam.t);
return 0;
}