I am working on a school project where I have to make a program that let the user enter information about new books, delete books or display all registered books.
The unexpected behavior is when I choose to display all books : THE SECOND BOOK'S TITLE ALWAYS print some strange random characters or about 15 empty lines while the rest remain normal.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int Pages,RlsYear,AtrNbr; //"Pages" stands for "the number of pages", "RlsYear" stands for "Release Year"
char Title[128],Genre[128],Authors[256];
}book;
int main()
{
int i,nb;
char ch1,Tmp[128],cln;
book* b = malloc(1 * sizeof(book));
nb=0;
puts("\n Enter your choice : ");
ch1=getch();
while (ch1 != EOF && ch1 != 'q')
{
switch(ch1) {
case 'n': // N to enter a new book
case 'N':
{
printf("\n enter the book's Title : ");
gets(b[nb].Title);
printf(" enter the book's Genre : ");
gets(b[nb].Genre);
printf(" how many pages does the book have ? ");
scanf("%d",&b[nb].Pages);
gets(cln); //i added those "gets(cln)" to avoid problems from "scanf" so you can just ignore them
printf(" when was the book released (year)? ");
scanf("%d",&b[nb].RlsYear);
gets(cln);
printf(" how many authors does this book have ? ");
scanf("%d",&b[nb].AtrNbr);
gets(cln);
strcpy(b[nb].Authors,"");
for(i=0;i<b[nb].AtrNbr;i++)
{
printf("\t\t enter the %d author : ",i+1);
gets(Tmp);
strcat(b[nb].Authors,Tmp);
strcat(b[nb].Authors," | ");
}
nb=nb+1;
book* B = realloc(b, nb+1 * sizeof(book));
b = B;
}
break;
case 'i': // I to display registered books
case 'I':
{
for(i=0;i<nb;i++)
printf("\n %s",b[i].Title);
}
break;
default:
printf("unknown choice !");
break;
}
puts("\n Enter your choice : ");
ch1=getch();
}
return 0;
}
I solved the problem when i changed the b.Title
size from 128 to 60.
Apparently the problem appears when the b.Title
size passes 80.
Can someone explain please? i'm more confused now