19

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?

Supernormal
  • 962
  • 8
  • 15

2 Answers2

21

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

giusti
  • 3,156
  • 3
  • 29
  • 44
8

In the first case, a itself occupies sizeof(int *) bytes of automatic storage, and that points to 10 * sizeof(int) bytes of dynamic storage.

In the latter case, b occupies 10 * sizeof(int) bytes of automatic storage. Because b is an array, there is no pointer.

So the first case uses more total bytes, but less on the stack (assuming a stack is in use for automatic storage).

If the total number of bytes being used is relatively small, automatic storage is typically fine. For larger amounts, dynamic storage is preferred. For stack implementations in particular, having too many automatic variables that are too large can overflow the stack.

dbush
  • 205,898
  • 23
  • 218
  • 273