Reputation:
I have a segmentation fault when i run my C program and i do not understand it. I am reading the header from a binary file that contains student structs.
this is the seg fault i get when i run it with gdb
Program received signal SIGSEGV, Segmentation fault. 0x0804850f in main () at aidb.c:49 49 }
I am under the impression that the segmentation fault is at line 49, however there's only the closing bracket of my main () method at line 49. This is my code, just in case it helps clarify things:
#include<stdio.h>
typedef struct {
char id_chars[4];
int file_size;
int section_table_offset;
int section_count;
} Header;
typedef struct {
int offset;
int num_entries;
int type; // legal value above
} SectionHeader;
int main(void) {
FILE *infile = fopen("file.bin", "r");
Header aidbheader;
//Reads the aidb file header
// fread(aidbheader, sizeof(Header),16, infile);
fread(&aidbheader.id_chars, sizeof(char),4, infile);
fread(&aidbheader.file_size, sizeof(int),1, infile);
fread(&aidbheader.section_table_offset, sizeof(int),1, infile);
fread(&aidbheader.section_count, sizeof(int),1, infile);
SectionHeader table[4];
fread(table, sizeof(SectionHeader), 48, infile);
printf("\nSectionHeader offset: %d \n", table[3].offset);
return 0;
} // this is line 49
Upvotes: 0
Views: 130
Reputation: 206647
You declare table
as:
SectionHeader table[4];
Then you try to read into table
48 objects of size sizeof(SectionHeader)
.
fread(table, sizeof(SectionHeader), 48, infile);
There isn't enough space in table
to hold that much data. Because of that, you write over memory that you are not supposed to. That is cause for undefined behavior. In your case, the undefined behavior manifests as segmentation fault when the program returns from main
.
You can fix that problem by changing the size of table
or changing the fread
line. Make sure that table
has enough space to read the data.
The other error in your code is that the id_chars
member of Header
is defined as:
int id_chars[4];
When you read data into it, you are using
fread(&aidbheader.id_chars, sizeof(char), 4, infile);
This by itself won't cause segmentation fault. It is a symptom of possibly buggy code. Make sure to change the definition of id_chars
to
char id_chars[4];
^^^ char not int
or change the fread
line to use:
fread(&aidbheader.id_chars, sizeof(int), 4, infile);
^^^^ int not char
Upvotes: 3