I’m familiarising mywself with C, and currently I’m learning about dynamic memory allocation. So, for instance, if, for whatever reason, I need a buffer that can hold ten floating-point numbers, I can do the following:
(1) float* buffer = malloc(sizeof(float) * 10);
The return value “buffer” of this function call will be a pointer to the start of the memory block. But alternatively, I could do the same with an array:
(2) float buffer[10];
Again, “buffer” is a pointer to the first element in the allocated memory.
Is there any reason why I should prefer (1) over (2)? The resources I’m relying on (online courses and a print book) claim that dynamic memory allocation with malloc
is preferable when you don’t know at compile time how much memory you’re going to need. I don’t understand what this is supposed to mean. After all, malloc
, just like the declaration of an array, needs the size of the required memory space as a parameter. Sure, there is no need to hard-wire that size; I can, for instance, calculate elsewhere in my program an integer variable “size” corresponding to the number of floats my buffer will need to hold:
(3) float* buffer = malloc(sizeof(float) * size);
But the same thing works with arrays:
(4) float buffer[size];
I read that memory created via malloc
is in the heap whereas arrays sit in the stack. But why would I care about this difference? It’s all coming out of the same overall memory that my computer has, after all. So the only difference that I can see is that malloc
allows for subsequent expansion with realloc
if I later decide that I want to add more elements. But as I understand it, realloc
is kind of a lucky shot: It works nicely if the additional memory (in the equired amount) happens to be available after the end of the originally allocated block; in that case, the new elements will be tacked on back-to-back. If no memory is available there, realloc
will allocate new contiguous memory elsewhere and copy the existing elements there. This is something that I can also do with arrays.