0

After watching Dynamic Memory allocation section and reading this i am a bit confused, if declaring an array
int array[10]; and allocating using malloc int* parray = malloc(10 * sizeof(int)); are the same why bother using malloc? it is more arcane and you need to remember to free the memory, also what is the point of saying "Dynamic" if using malloc you get the same array as with the declaration method? I am aware that malloc allocates memory in the heap while declaring a variable in the stack but i don't see the difference.

3 Answers 3

2

In addition to the points made by @MARS and @NullityNull, there are advantages and disadvantages to both methods.

Allocating memory on the stack is more convenient because it automatically cleans up after itself when the variable is no longer in scope. Sometimes this is called "garbage collection". However, this convenience comes at a cost of fixed size: the limitation mentioned in both of the other answers.

Allocating memory on the heap requires more attention to detail, since everything that you manually malloc() must be explicitly freed later with free(). But this additional hassle can often be worth it, because it gives you the flexibility of dynamically resizing a buffer when it fills up. The manual page for realloc() may help you to understand the advantages to this:

man realloc
0

The difference between the two is that you use an array of chars when you know the number of elements that it will hold during compile time. You use malloc with pointers when you don't know how many elements the array will have to hold before it's compiled.

While the same thing can be accomplished using both methods in some situations that is not always the case, which brings the need for two different ways of memory allocation. It's like comparing a philips and a flat head screwdriver: the flat head screwdriver might fit some philips screws, but the philips screwdriver is more suited for the job.

0

In fact there is no difference, except when using an array one must declare its type and size before use (i.e., before compiling). Then we can not change its size. This is a very serious limitation. To overcome it, we have the possibility to use malloc() (and its family). malloc() should be used when we need to allocate memory during program execution, and we do not know beforehand the size of the array.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .