Because you're allocating space for some_size number of pointers to integers and assuming that some_size number of integers fit in it.
This will always work (I think), but is never a good idea because you're just allocating space for a different data structure than the one you actually have. Hence why you should always always just do int *var = malloc(some_size * sizeof(*var)) because it is impossible to allocate the wrong amount of space here, even if I later change it to long long *var without looking at the right hand side.
(or for a more realistic scenario where the former becomes a nightmare to maintain, if var is actually defined in some struct and there are dozens of methods interacting with this struct that all need to allocate or reallocate var)
View all comments
Show parent comment
12
u/Magnus_Tesshu Nov 01 '21 edited Nov 01 '21
Because you're allocating space for some_size number of pointers to integers and assuming that some_size number of integers fit in it.
This will always work (I think), but is never a good idea because you're just allocating space for a different data structure than the one you actually have. Hence why you should always always just do
int *var = malloc(some_size * sizeof(*var))because it is impossible to allocate the wrong amount of space here, even if I later change it tolong long *varwithout looking at the right hand side.(or for a more realistic scenario where the former becomes a nightmare to maintain, if
varis actually defined in some struct and there are dozens of methods interacting with this struct that all need to allocate or reallocatevar)