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))
- The cast is not necessary and just adds clutter
- Using
sizeof(*p)
instead of sizeof(int)
is safer
Related: Do I cast the result of malloc?
I think both the malloc statements are dynamic memory allocations
and you are right.Is there something wrong with my reasoning?
No. – Endosporemalloc
is dynamic allocation and it even says it in the manual page:malloc, free, calloc, realloc - allocate and free dynamic memory
– Justenmalloc()
is, at best, redundant and may hide an error the compiler would catch in the absence of the cast. – Thinnishint arr[100]
syntax, but then he introduced us withmalloc
. Then he told the first line as you see in the question. – Mcmillanint p[5]
could be convenient for the problem... (but technically the first call is still dynamic allocation here). – Hygrographp= malloc(sizeof *p * n);
(no cast, no type). Easier to code right, review and maintain. – Prosecute