How can we find MEMORY SIZE from a given memory pointer?

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 the MEMORY from the memory pointer P in func ()?

+5
source share
5 answers

In C (or even C ++, I believe) there is no legal way to do this. Yes, it somehow freeknows how much malloced was, but it does it so that it is not visible or accessible to the programmer. For you, a programmer, he could do it by magic!

, malloc , . , ( , malloc (, )) -.

+10

, , , , :

int *p = (int *) malloc(10);

-, . - :

void func(int *p, size_t size)
{
  printf("Memory address 0x%x has %d bytes allocated for it!\n", p, size);
}

int main()
{
  int my_bytes = 10;
  int *p = malloc(my_bytes);
  func(p, my_bytes);

  return 0;
}
+3

UNIX- , msize stdlib, , . , - .

msize, , malloc realloc, , ( , , .)

+2

Microsoft Windows, Windows API Heap * , (C ). HeapAlloc, HeapReAlloc, HeapFree , , HeapSize.

, , - malloc , . , , , . ( C, ...).

+1

-, , , .

, , - C. , , . , , , .

, . , , . , , , , - , .

0

All Articles