Dynamic memory allocation in C

The question will probably seem simple, but not for me. The size is unknown in advance, it all depends on the user's desire. Structure Declaration:

struct Book* books;

Then, if the person wants, he can create 1 more book, I allocate memory for him in this way:

books = (struct Book*)malloc(sizeof(struct Book));

But as I understand, I do not add more space to the memory, but only clean and allocate new memory, so I can only have 1 book in the structure. How to add a place to memory over time as needed add 1 book? To announce in advance how much space is not optimal, since we do not know how much will need to be added, everything is decided in prime time.

Or is everything solved by declaring struct Book** books?

Author: Andrea Jones, 2020-04-05

2 answers

To reallocate memory, try using realloc (). https://ru.cppreference.com/w/cpp/memory/c/realloc

 1
Author: Dmoon, 2020-04-05 12:01:40

Realloc is not an option in this case, since what it does is allocate dynamically more space in memory, then copy the data and the previous smaller space, and then clear that smaller space. Imagine you already have 1 GB of memory occupied and you are doing a realloc of 1 GB + 1 byte. In this case, you will need to re-allocate 1 GB + 1 byte, copy 1 GB and clear 1 GB. Very unproductive! In two cases, you need to implement an abstract data type list, single-linked or double-linked. You can use ready-made solutions from many libraries (glib, for example) or write it yourself, including operations for creating a list, adding an element, deleting an element, and searching for an element. Each element of the spmsca will contain as data a pointer to the dynamically allocated memory for the structure of the book with information about it.

 0
Author: Dmitry Safonov, 2020-04-05 12:31:22