Reputation: 35
#include<stdio.h>
int main(){
int * ptr=(int *)malloc(40);
printf("%d",sizeof(ptr));
}
When I'm running this, output is coming as 8...what is happening here...why is output 8?
Upvotes: 0
Views: 171
Reputation: 11
I have tried this on my Windows 32bit machine, i am getting ans 4 bytes, i think as ptr is a pointer to int show its showing the corre
Upvotes: 0
Reputation: 2773
malloc()
returns a pointer to 40 bytes of memory (probably 10 ints) and assigns it to ptr
. The reason sizeof(ptr)
is 8 is because you are using a 64 bit machine and pointers are 8 bytes in size.
You should use sizeof()
inside the malloc()
because it's good form and avoids problems if the type ever changes size (crossing platforms or whatever). If you really want space for 10 ints then use:
int *ptr = malloc(10 * sizeof *ptr);
This allocates 10 lots of the size of the type ptr
points to, in this case int
. The benefit of doing this is you can change the type without changing the malloc()
Upvotes: 2
Reputation: 1
The sizeof
operator is a compile time operator, and the size of any pointer is 8 bytes on your machine.
There is no way to retrieve the dynamic size of the malloc
-ed memory zone. You have to know it otherwise, or to keep it somewhere.
You might consider using Boehm's conservative garbage collector then you'll call GC_malloc
instead of malloc
, you won't need to call free
(or GC_free
), and you could use GC_size(p)
to get the approximate size of the previously GC_malloc
-ed memory zone starting at p
(but I don't recommend using GC_size
).
If using malloc
on Linux, learn how to use valgrind to hunt memory leak bugs, and compile with gcc -Wall -g
Upvotes: 2
Reputation: 67211
ptr is a pointer.its printing the size fo the pointer on your system. as ptr holds an address, 8 bytes is the size required to hold an address on a 64 bit machine. This is compiler specific.You cannot retrieve the size allocated to a pointer.
if you getting this doubt,then you should also get a doubt of how does free() will free the memory without knowing the size that has been allocated to the pointer.
Upvotes: 0
Reputation: 25337
The variable ptr
is a pointer to int, an your system it happens to have the size of 8 byte.
Upvotes: 0