Is there any difference in the memory usage of these two code lines?
int *a = malloc( 10 * sizeof(int) );
int b[10];
The first line should allocate memory for 10 ints and 1 pointer. But I'm not sure about the second. Will that also allocate memory for 10 ints and 1 pointer, or just 10 ints?
An int[] array thus uses 28 bytes plus 4 bytes for each int. An Integer[] array uses 28 bytes plus 4-8 bytes to reference each Integer object plus 28 byte for each unique Integer object.
malloc(10) allocates 10 bytes, which is enough space for 10 chars. To allocate space for 10 ints, you could call malloc(10 * sizeof(int)) .
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. If space is insufficient, allocation fails and returns a NULL pointer.
Simply put:
int *a = malloc( 10 * sizeof(int) );
Allocates at least sizeof(int*)
bytes of automatic storage for the pointer *a
. When malloc
is called, this will allocate at least sizeof(int) * 10
bytes of dynamic storage for your program.
On the other hand:
int b[10];
Allocates at least sizeof(int) * 10
bytes of automatic storage. There are no pointers here. When you use the name b
in an expression (example: a = b
), it decays into a pointer. But a
is a pointer and b
is an array. Check this on C FAQ: C-FAQ Sec. 6: arrays and pointers.
In the most usual case, "automatic storage" means the "stack", and "dynamic storage" means the "heap". But that's not always true. You may want to read a bit of discussions about this terms in this question: "Why are the terms “automatic” and “dynamic” preferred over the terms “stack” and “heap” in C++ memory management?".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With