Dynamically Allocating Structures and Structure Members
Explore how to dynamically allocate structures and their members in C, including arrays and strings. Understand using malloc, calloc, and strdup for flexible memory management, preventing stack overflow, and how to properly free allocated memory.
Introduction
We can dynamically allocate structures like we allocate any other data type.
Let’s revisit the bookstore example. Here’s the code for reference:
We have a TBookStore structure, which contains a list of books. We defined the list of books as an array of 1,024 elements. This array can’t grow, and we can’t decide its size at compile time since we don’t know the number of books.
Moreover, up to this point, we allocated each structure on the stack. We can run into a stack overflow exception if the structures are too big. It means we can’t use a huge number as the size of our array instead of 1,024 since we may run out of space.
Note: It’s good practice to dynamically allocate large structures. Avoid placing them on the stack to avoid a stack overflow error.
Dynamically allocating TPoint
Before we fix the bookstore code, let’s take a simple example and learn how to allocate a single structure.
Let’s reconsider the point structure. ...