Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory does int x[10] allocate?

Tags:

c

malloc

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?

like image 654
Supernormal Avatar asked Jan 04 '17 15:01

Supernormal


People also ask

How much memory does an int array use?

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.

How many bytes will malloc 10 allocate?

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)) .

What is the memory allocation of 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.


1 Answers

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?".

like image 104
giusti Avatar answered Sep 21 '22 12:09

giusti