2

I need to dynamically allocate array of structs and perform some operations on it, then deallocate the memory. When I try to deallocate memory like that

for (int i = 0; i < booksAmount; i++) {
    free(myArray[i])
}

Here is the link to code

https://repl.it/@Xyrolle/Structures

I need to make so printList function will not print books array after deallocation.

Also, do you have any suggestions on how to manage memory more efficiently?

Thank you.

Serghey Hmeli
  • 63
  • 1
  • 6

2 Answers2

0

The code would look like this:

struct Book *booksList = NULL;
allocList(&booksList, booksAmount);

void allocList(struct Book **myArray, int booksAmount) {
    *myArray = malloc(sizeof(struct Book) * booksAmount);
    printf("memory for %d books was allocated \n", booksAmount);
}

Now to free the allocated memory. You allocated memory once for the array of books, thus you'll need exactly one free:

free(booksList);

Also, note that I removed the cast from malloc. This post has very good points on why you should not cast it.

Saucy Goat
  • 1,587
  • 1
  • 11
  • 32
  • Thank you for casting advice. When I try to deallocate memory like that only the "title" field of first structure is deallocated, but the rest are still in memory and could be printed to the screen. – Serghey Hmeli Dec 24 '19 at 15:48
  • @SergheyHmeli - you are confusing `free`ing the memory (telling the compiler it can reuse the memory) and whether values still exist at that location because they have not been overwritten yet. After you `free` memory, any attempt to access the values invokes *Undefined Behavior* -- you no longer own that memory. There is no guarantee what will be at those addresses. If there have been no further allocations, all the original values may still be there -- but you cannot make use of that memory anymore -- for that reason -- there is no guarantee what will be there. – David C. Rankin Dec 24 '19 at 16:00
0

Your approach to allocate memory is not correct. As you are using structure for each book. You should allocate memory separately for each record. Because you may not store all book record at once. For Example: You have maximum no. of books as 100, but now you have information of 10 books. With your approach memory for 90 books will be wasted.

void allocList(struct Book **myArray, int booksAmount) {
        int i;
        for(i = 0;i < booksAmount; i ++) {
            *myArray = (struct Book*) malloc(sizeof(struct Book));
        }
}

Dellaocate memory:

for (i = 0; i < booksAmount; i ++) { 
    free(myArray[i]); 
}