Ad

Is Malloc Dynamic Memory Allocation?

I was told by an instructor that p = (int*)malloc(5 * sizeof(int)) is NOT dynamic memory allocation and that p=(int*)malloc(n * sizeof(int)) is dynamic memory allocation.

The instructor was talking about basic data structures and was teaching arrays. He had told us the traditional way to create arrays using the int arr[100] syntax, but then he introduced us with malloc.

According to him as the memory size doesn't change it's not dynamic I guess.

From what I could gather from the internet, malloc assigns memory at runtime, and when memory is assigned at runtime its dynamic memory allocation. So I think both the malloc statements are dynamic memory allocations. Is there something wrong with my reasoning?

Ad

Answer

Usually, we do refer to calls to malloc as dynamic allocation, irregardless if you're using a variable or constant. Even the man page for malloc calls it like that:

malloc, free, calloc, realloc - allocate and free dynamic memory

So for your instructors claim:

The instructor was talking about basic data structures and was teaching arrays. He had told us the traditional way to create arrays using the int arr[100] syntax, but then he introduced us with malloc.

According to him as the memory size doesn't change it's not dynamic I guess.

Well, in some sense he has a point if you look strictly at what "dynamic" means in a more general way. Right now we have a convention that calls all malloc dynamic allocation. This convention could have been the way your teacher claims without any problems. But it is not.

Furthermore, according to your teachers reasoning, using VLA:s (variable length array) or alloca with a variable would be considered dynamic allocation, but it is not. A VLA can be declared like this: int arr[n], or it's alloca equivalent: int *arr = alloca(n*sizeof(*arr)).

So even if you could argue that your teacher has a point, it would only cause confusion since it goes against the convention.

Also, the most dynamic thing about using malloc is that the allocation can be resized later. You cannot do that with arrays, not even VLA:s. And you cannot do it to memory you have allocated with alloca.

But as a sidenote, I do question your teachers competence if they teach you to write

p = (int*)malloc(n * sizeof(int)) 

instead of

p = malloc(n * sizeof(*p))
  1. The cast is not necessary and just adds clutter
  2. Using sizeof(*p) instead of sizeof(int) is safer

Related: Do I cast the result of malloc?

Ad
source: stackoverflow.com
Ad