Reputation:
Before starting I know that there has been quite a lot of questions about this and I hope that my question is not redundant. I have read quite a lot of things on the internet, and I have a specific question. When allocating memory in C language, what is the best way to allocate memory.
So imagine I want to allocate a int* nb
, so is there a better way to allocate the memory?
First solution I have read:
nb=malloc(sizeof *nb);
Second solution I have read:
nb=malloc(sizeof(nb));
Third solution I have read:
nb=malloc(sizeof(int*));
Th reason I am asking this is because I have read on the internet, all three solutions, and if I understood well, that the allocation size may differ depending the system you are on, so the reason for using sizeof(nb)
, which may allocate more memory than sizeof(int)
. So am I wrong ?
[EDIT]
The aim here is mostly to allocate an array of arbitrary size
[/EDIT]
Thanks for any help and again, hoping my question is not redundant
Upvotes: 1
Views: 262
Reputation: 37232
The advantage of the first solution is that you can change the type in one place (e.g. from int* nb
to double* nb
) and the "malloc()" will automatically be correct for the new type and won't need to be modified.
The advantage of the third solution is that there are more visual hints for the programmer. E.g. if you see nb=malloc(sizeof(int));
you don't need to find the type of nb
to determine what it's allocating.
In theory; which is preferred depends on context (which advantage is more important at the time) and the former is more likely to be better. In practice, I have a habit of always doing the latter and then being disappointed that mistakes aren't detected by the compiler's type checking. :-)
Upvotes: 1
Reputation: 4282
1) Normally, we declare and statically allocate int
variable like below:
int nb;
2) If we want to create an array or for some reasons, we can declare a dynamically allocatable variable (a pointer):
int* nb;
In case 2) we need to allocated a memory block to the declared variable:
nb = (int*) malloc( sizeof(*nb) );
For single int
storage we use sizeof(int)
or sizeof(*nb)
.
Because nb
is a pointer to int
, typeof(*nb)
is int
.
Upvotes: 0
Reputation: 1271
int *IntPtr=NULL;
IntPtr=malloc(100*sizeof(int));
is the same as
int *IntPtr=NULL;
IntPtr=malloc(100*sizeof(*IntPtr));
because IntPtr is of type int*
so dereferencing it (i.e.*IntPtr ) leads to type int
On the other hand:
nb=malloc(sizeof(nb));
is a bad choice, since the sizeof(nb)
is the size of the pointer itself, i.e. the size of the address in memory. On 32 bit systems this is always 4 no matter what the type of nb
is.
For dynamic memory allocation, you should check realloc
Upvotes: 3