Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we find MEMORY SIZE from given memory pointer?

Tags:

c

void func( int *p)
{
  // Add code to print MEMORY SIZE which is pointed by pointer P.
}
int main()
{
  int *p = (int *) malloc (10);
  func(p);
}

How can we find MEMORY SIZE from memory pointer P in func() ?

like image 455
siva Avatar asked Oct 03 '10 18:10

siva


People also ask

How do you calculate the size of memory pointed by pointer?

If you allocated memory for a single value, you probably used sizeof() to find the amount of space needed for that value's type. You should know what that type was, too, because it's the type of the pointer. So you can just call sizeof() again on the same type.

What is the memory size of a pointer?

Pointers take up the space needed to hold an address, which is 4 bytes on a 32-bit machine and 8 bytes on a 64-bit machine.

How can you tell the size of memory allocated by malloc using pointers?

It is impossible to know how much memory was allocated by just the pointer. doing sizeof (p) will get the size of the pointer variable p which it takes at compile time, and which is the size of the pointer. That is, the memory the pointer variable takes to store the pointer variable p .


1 Answers

There is no legal way to do this in C (or even C++ I believe). Yes, somehow free knows how much was malloced but it does so in a way that is not visible or accessible to the programmer. To you, the programmer, it might as well have done it by magic!

If you do decide to try and decode what malloc and free does then it will lead you down the road to proprietary compiler implementations. Be warned that even on the same OS, different compilers (or even different versions of the same compiler, or even the same compiler but using a third party malloc implementation (yes such things exist)) are allowed to do it differently.

like image 189
slebetman Avatar answered Nov 15 '22 04:11

slebetman