2

I've just been playing around in C for the first time, and I'm at a loss as to why malloc is not giving me the amount of memory that I'd expect it to. The following code:

printf("Allocating %ld bytes of memory\n", 5*sizeof(int));
int *array = (int *) malloc(5*sizeof(int));
printf("%ld bytes of memory allocated\n", sizeof(array));

results in:

Allocating 20 bytes of memory
8 bytes of memory allocated

I've checked that I'm indeed calling malloc to give me 20 bytes, but don't understand why after calling malloc, the pointer only has 8 bytes.

Meegul
  • 131
  • 2
  • 7

2 Answers2

5

array is not an array but an int *. So it's size will always be the size of the pointer.

The sizeof operator does not tell you how much memory was dynamically allocated at a pointer.

If on the other hand you had this:

int array2[5];

Then sizeof(array2) would be 20, assuming an int is 4 bytes.

dbush
  • 205,898
  • 23
  • 218
  • 273
5

The sizeof operator tells you the size of its operand. array has type int* (pointer to int) which occupies eight bytes on your platform. The sizeof operator cannot find out how long the array array points to actually is. What is returns is not indicative about how much memory has been allocated.

The malloc() function either fails (in which case it returns NULL) or succeeds in which case it returns a pointer to a memory region at least as large as you need it.

fuz
  • 88,405
  • 25
  • 200
  • 352