Main Content

Dynamic Memory Allocation in C

Archive - Originally posted on "The Horse's Mouth" - 2008-06-09 15:13:09 - Graham Ellis

In C, you give fixes sizes for arrays at compile time .... which means you either have to know ahead of time how big something will be, or allow enough space for the worst case scenario.

Rather than using arrays, you can use pointers to the memory heap - and in this way you can use functions to give you dynamic memory allocation:

malloc - allocate a specific memory block
calloc - allocate an array of specific memory blocks
realloc - expand or contract a calloced block
free - release a malloced block
cfree - release a realloced block

There's an example showing how these functions can be used to dynamically load a file with a variable number of variable length records here