Main Content

Allocating memory dynamically in a static language like C

Archive - Originally posted on "The Horse's Mouth" - 2013-06-30 21:19:38 - Graham Ellis

From last weeks' C course - a complete example showing dynamic memory allocation - reading in any file of data, lines of varying length, and packing them in neat. Source code [here].

There's an issue with reading data of unknown size into a fixed declaration language like C... allocation stack memory isn't clever either, as it makes it impractical to pass data generated in one function on to its sibling - the data's lost on return to the parent so it doesn't have it to pass to the brother or sister.Solution! - Allocate memory on the heap. You can do that for each record using calloc. But that's not going to be the solution for the array of pointers to the records as we don't know how many of those there will be. We'll use realloc which lets us allocate and then extend memory. The call's like this:

  mydata = realloc(mydata,(nread+1) * sizeof(char *));

You'll note that the ingoing pointer (set to NULL before the very first call) is also set into the return variable - that way, the C function can shift the data around if it needs to, change the pointer, and return you a new address to an extended area or it can just return the same value if it's got enough free memory starting at the location passed in. It's really neat!

I'll show you this from first principles - help you to learn it - on the course.