Anurag Vishwa Anurag Vishwa - 20 days ago 6
C Question

Getting error in C "Segmentation fault (core dumped)"


Getting segmentation dumped error,while running the code, it compiles properly though.
When i run the program it asks me for the input
After entering a value to the name array, it results into segmentation fault.
Please help me with the error free solution.


#include<stdio.h>

struct book
{
char name[20];
char author[20];
int price;
};

struct pages
{
int page;
struct book b1;
} *p;

int main()
{
printf("\nEnter the book name , author , price, pages\n");
scanf("%s %s %d %d",p->b1.name,p->b1.author,&p->b1.price,&p->page);

printf("The entered values are\n");

printf("The name of book=%s\n",p->b1.name);
printf("The author of book=%s\n",p->b1.author);
printf("The price of book=%d\n",p->b1.price);
printf("The pages of book=%d\n",p->page);



return 0;


}

Answer

You haven't allocated memory for p. Add code to allocate memory for p and deallocate that memory before returning from main. Use

int main()
{
   p = malloc(sizeof(*p));

   printf("\nEnter the book name , author , price, pages\n");
   scanf("%s %s %d %d",p->b1.name,p->b1.author,&p->b1.price,&p->page);

   ...

   free(p);
   return 0;
}
Comments