I am trying to figure out the difference between structs on the heap and on the stack. I have the following structs, for Book, Author and Shelf. Book has multiple authors and Shelf has multiple books.
struct Author {
char name[NAME_LENGTH];
};
struct Book {
char title[TITLE_LENGTH];
struct Author authors[AUTHORS_PER_BOOK];
int author_count;
};
struct Shelf {
struct Book books[BOOKS_PER_SHELF];
int book_count;
};
I have a bunch of functions of creating the Author and Book structs, with specified name and title. And a function for adding authors to book. I understand that C is strictly pass by value, so I used a pointer to the book in add_authors_to_book function. These functions are created locally, I am assuming they are on the stack(?).
struct Author new_author(char name[]) {
struct Author author;
strcpy(author.name, name);
return author;
}
struct Book new_book(char title[]) {
struct Book book;
strcpy(book.title, title);
book.author_count = 0;
return book;
}
void print_book(struct Book book) {
printf("%s\nby", book.title);
int i, n;
for (i = 0, n = book.author_count; i < n; i++) {
printf(" %s,", book.authors[i].name);
}
printf("\b.\n");
}
void add_author_to_book(struct Book *book, struct Author author) {
book->authors[book->author_count] = author;
book->author_count++;
}
I want the shelf to be on the heap. I am allocating memory for it and freeing it below.
struct Shelf *new_shelf() {
struct Shelf *shelf = malloc(sizeof(struct Shelf));
shelf->book_count = 0;
return shelf;
}
void delete_shelf(struct Shelf *shelf) {
free(shelf);
}
void print_shelf(struct Shelf *shelf) {
printf("Shelf has the %d book(s),\n", shelf->book_count);
int i, n;
for (i = 0, n = shelf->book_count; i < n; i++) {
print_book(shelf->books[i]);
}
}
My question is regarding adding the books to the shelf. Below I am assigning the book struct to the shelf’s book at it’s last index. Where does this struct Book reside, on the Heap or on the Stack? Will C create clone of the entire Book structure including the authors automatically when passing it to the add_book_to_shelf? Does pass by value work with such nested structs?
Also how do you go about freeing up the memory used by books and it’s authors?
void add_book_to_shelf(struct Shelf *shelf, struct Book book) {
shelf->books[shelf->book_count] = book;
shelf->book_count++;
}
Here’s my test code,
int main(int argc, char *argv[]) {
struct Shelf *shelf = new_shelf();
struct Book book = new_book("Freakonomics");
add_author_to_book(&book, new_author("Stephen Dubner"));
add_author_to_book(&book, new_author("Steven Levitt"));
add_book_to_shelf(shelf, book);
print_shelf(shelf);
delete_shelf(shelf);
return 0;
}
You’re copying the book in add_book_to_shelf, which means it will be on the heap.
The book that you created in main will be on the stack, (since it is an automatic variable,) but in add_book_to_shelf the book is copied into the books array which is allocated as part of the shelf on the heap.