【发布时间】:2015-05-12 04:49:25
【问题描述】:
我很难理解我在这里做错了什么。我正在编写一个程序来组织书籍数据库。我正在使用链接列表将书籍结构保存到内存中。在输入书籍信息时,我得到了
分段错误(核心转储)
输入第一个值后,书籍标识符。在我的 AddBook 函数中,我创建了一个临时书结构 (aBook)。然后我要求用户输入新书的标识符,然后尝试将其保存到 aBook 的标识符属性中。这就是发生错误的地方。
无论如何,我在程序的顶部包括了库、声明函数等,还包括了菜单函数和 addbook 函数,因此希望有人能发现我的错误。提前致谢。
我的代码的顶部:
//Libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
//only 10 books maximum
#define MAX 10;
//function prototypes
void fileInput();
void menuSystem();
int writeAndCloseFile();
void addBook();
void takeOutBook();
void returnBook();
void deleteBook();
void viewAllBooks();
void viewBook();
void viewYearCollection();
int exitSystem();
bool isEmpty();
//The File
FILE *fp;
//LinkedList Initialization
struct bookData {
//book variables
char* identifier;
char* title;
char* author;
int year;
bool status;
char* customer;
int timesTakenOut;
char* genre;
};
//struct for one node
struct node {
struct bookData *element;
struct node *next;
};
//first and last nodes
struct node *firstBook = NULL;
struct node *lastBook = NULL;
菜单功能和AddBook功能(发生错误的地方):
//MENU SYSTEM FUNCTION
void menuSystem()
{
int chosenOption = 0;
printf("****************\n\n");
printf(" MENU\n\n");
printf("****************\n\n");
printf("1 - Add book\n");
printf("2 - Take out book\n");
printf("3 - Return book\n");
printf("4 - Delete book\n");
printf("5 - View all books\n");
printf("6 - View book\n");
printf("7 - View Year Collection\n");
printf("8 - Exit\n\n");
printf("Chosen Option: ");
scanf("%d", &chosenOption);
//1. ADD BOOK
if(chosenOption == 1)
{
addBook();
}else if(chosenOption == 2){
//2. TAKE OUT A BOOK
takeOutBook();
}else if(chosenOption == 3){
//3. RETURN A BOOK
returnBook();
}else if(chosenOption == 4){
//4. DELETE A BOOK
deleteBook();
}else if(chosenOption == 5){
//5. VIEW ALL BOOKS
viewAllBooks();
}else if(chosenOption == 6){
//6. VIEW A BOOK
viewBook();
}else if(chosenOption == 7){
//7. VIEW YEAR COLLECTION
viewYearCollection();
}else if(chosenOption == 8){
//8. EXIT SYSTEM
printf("\n\nGoodbye!\n\n\n\n");
exitSystem();
}
}
void addBook(){
printf("\n*** ADDING BOOKS ***\n");
struct node *aBookNode;
struct bookData *aBook;
aBook = (struct bookData *)malloc(sizeof(struct bookData));
if (aBook == NULL)
printf("Error - no space for new book data\n\n\n");
else
{
//INPUT BOOK INFO
//Identifier
printf("\nIdentifier(####-####): ");
scanf("%9s", aBook->identifier);
fflush(stdin);
//Title
printf("Title: ");
scanf("%s", aBook->title);
控制台输出(在我输入一个随机数作为标识符之后):
Could not open the file book.dat
****************** The database is empty. Books will need to be manually entered ******************
*** ADDING BOOKS ***
Identifier(####-####): 1234-1234
Segmentation fault (core dumped)
【问题讨论】:
标签: c pointers segmentation-fault