Reputation: 39
Writing out this library program and I'm receiving a Segmentation Fault 11 when I run through my terminal. At first when debugging it seemed to be located somewhere with the structs but then it was giving me issues where I had my FILE pointer declared. Can someone shed some light on this matter?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 40
#define MAX_BOOKS 1000
struct book
{
char title[MAX_LENGTH];
char author[MAX_LENGTH];
char subject[MAX_LENGTH];
}*Book;
struct library
{
struct book collection[MAX_BOOKS];
int num_books;
}*lib;
int main()
{
struct library *lib;
char title[MAX_LENGTH], author[MAX_LENGTH], subject[MAX_LENGTH];
Book = NULL;
lib->num_books = 0;
int events = 0, selection = 0;
FILE *ifp;
ifp = fopen("library.txt", "r");
if (ifp == NULL)
{
printf("\nFile not found\n");
exit(0);
}
fscanf(ifp, "%d", &events);
for (int i=0;i<events; i++)
{
Book = NULL;
fscanf(ifp, "%d", &selection);
switch (selection)
{
case 1:
fgets(title, MAX_LENGTH, ifp);
fgets(author, MAX_LENGTH, ifp);
fgets(subject, MAX_LENGTH, ifp);
strcpy(Book->title, title);
strcpy(Book->author, author);
strcpy(Book->subject, subject);
lib->num_books += 1;
//addBook(lib);
break;
case 2:
lib->num_books -= 1;
//deleteBook();
break;
case 3:
//search;
break;
case 4:
break;
case 5:
break;
default:
printf("Invalid command\n");
break;
}
}
fclose(ifp);
return 0;
}
Upvotes: 2
Views: 434
Reputation: 16607
lib->num_books = 0;
This is creating problem. You have not initialized lib
.
Allocate memory to it -
lib=malloc(sizeof(struct library));
Also don't forget to free
the allocated memory.
Upvotes: 2
Reputation: 91
1)Error is in the following line lib->num_books = 0;
The pointer variable lib is deferenced without initialization.
2) One more error is, you are opening file for read operations "r", but trying to use the file for write operations.
Upvotes: 0