0
char* pointer;
pointer = malloc (20000);

printf("%d", sizeof(pointer));
//output: 8

I was expecting 20000 for the output since I reserved 20000 bytes with malloc. But, it returned 8. Why is this happening?

slow
  • 805
  • 3
  • 13
  • 27
  • Ok I got what you mean. You don't need to go all around and blame on me for asking something that may have been answered already. It happens. – slow Mar 11 '13 at 06:11

4 Answers4

4

you must be using 64 bit system/OS, thats why it printed 8 for printf("%d", sizeof(pointer));

when you declare char *p; it will reserve space equalto sizeof(char *) in you memory.

now if the system is 64-bit it will reserve 8 bytes or if it is 32-bit then it will reserve 4 bytes.

now

char* pointer;
pointer = malloc (20000);

when you define pointer = malloc(20000) it will reserve a block of 20000 bytes in memory where pointer points to the first byte of that block it doesnt allocates 20000 bytes to pointer.

Kinjal Patel
  • 405
  • 2
  • 7
2

sizeof returns the size of the type you passed to it.
The type is char * and it just points to a memory location of size 20000.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Then what should I do to get the size of memory allocated? – slow Mar 11 '13 at 06:05
  • @ProgrammingNerd If this isn't asked like 100000000 times on SO, then it isn't at all. –  Mar 11 '13 at 06:05
  • 4
    @ProgrammingNerd: You allocated it, so you should keep track of it through your own bookkeeping. As for the program, it does its own internal bookeeping to free appropriately the amount of memory allocated on a `free` call. – Alok Save Mar 11 '13 at 06:06
0

sizeof is a compile-time operator. It only knows the size of the pointer (here, 8 bytes) and not the size of whatever it points to. sizeof doesn't exist at runtime.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

sizeof gives you the size of the pointer variable, not of the area it points to.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75