Search code examples
cstructuredynamic-memory-allocation

Why my structures do not display?


I am working on this structure memory allocation. Can someone help me figure out why it displays blanks for the author, title and id. The input is not kept on to be passed on the print function and I can't figure out why. Here is my code:

#include <stdio.h>
#include <stdlib.h>

struct book{
 char author[16];
 char title[16];
 int id; 
};

int i, n;

void add_records(struct book *b);
void print_records(struct book *b);

int main(int argc, char *argv) {

struct book *someBook; 
someBook = (struct book*) malloc(sizeof(struct  book));
add_records(someBook);
print_records(someBook); 

 return 0;
}


void add_records(struct book *b){
fprintf(stderr, "How many items do you want to add\n");
scanf("%d", &n);
b = (struct book*) malloc(n * sizeof(struct book));

for(i = 0; i < n; i++){
fprintf(stderr,"add author\n");
scanf("%s", (b + i)->author);
fprintf(stderr,"add title\n");
scanf("%s",(b+i)->title);
fprintf(stderr,"add Id: \n");
scanf("%d", &(b+i)->id);
}
}

void print_records(struct book *b){
b = (struct book*) malloc(sizeof(struct book));
for(i = 0; i < n;  ++i){
printf("Author: %s\t Title: %s\t Id: %d\n", (b+i)->author,(b+i)->title,(b+i)->id);
}
}

Solution

  • You allocate a book in main, pass it to add_records. Then allocate another book in add_records. Write into that second book. Return from add_book (leaking the filled in book) and going back to the untouched book in main.

    Then you call print_records, where you pass the book from main,. Then immediately create another empty book, print it's details and return leaking another book).

    You never once touch the original book you started with in main...

    Solution: get rid of the b = (struct book*) malloc(sizeof(struct book)); lines in add_records and print_records.