-1

why the ptr have the same size even tho I was expecting the size of ptr to be 5*size(int)/4 = 20 but I got the current size is 8 and also the new size is 8, any explanation pls?

 int *ptr;

 ptr = (int*)malloc(5 * sizeof(int));
 printf("current size is %ld\n", sizeof(ptr));

 for (int i = 0; i < 5 ; i++)
 {
     ptr[i] = i + 1;
 }
    
 for (int i = 0; i < 5 ; i++)
 {
     printf("%d\n",*(ptr + i));
 }
  
 ptr = (int*)realloc(ptr, 10 * sizeof(int));

 printf("new size is %ld\n", sizeof(ptr));
   
 for (int i = 0; i < 5 ; i++)
 {
     printf("%d\n", *(ptr + i));
 }
Chris
  • 26,361
  • 5
  • 21
  • 42
  • `sizeof(ptr)` gives the size of the pointer (which is fixed) and not the size of what it points to. You need to track the size yourself. – kaylum Oct 09 '21 at 20:40
  • [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Ed Heal Oct 09 '21 at 20:43
  • if a allocate 5*size(int) to ptr, do I give to ptr 20 addresses to work on? and how the pointer keeps tracking the addresses given, coz the addresses can't be like *****1,*****2,*****3,... so they gonna be in different places on the memory or am wrong? – abdeddaim mansar Oct 09 '21 at 21:13

2 Answers2

1

Any pointer on a 64-bit PC will probably be 64 bits, or 8 bytes. You're printing the size of the pointer itself, not the entire block of memory it points to.

See the article @kaylum pointed to in comments. How to determine the size of an allocated C buffer?

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Re “Any pointer on a 64-bit PC will be 64 bits, or 8 bytes”: The size of a pointer is determined by the C implementation, not the system. I have worked on a C implementation that used 32-bit pointers on a 64-bit architecture, because it was designed to save space in applications that used large numbers of pointers but did not need more than 2^32 bytes of memory. A C implementation might also use pointers larger than the address space requires, to provide additional features such as authentication or bug detection. – Eric Postpischil Oct 09 '21 at 20:46
  • Edited to account for 64-bit pointers being the _probable_ pointer size on 64-bit systems. – Chris Oct 09 '21 at 20:47
0

The approach you're attempting will work with stack-allocated arrays, but not with heap-allocated pointers.

comp.lang.c FAQ list · Question 7.27 -

Q. So can I query the malloc package to find out how big an allocated block is?

A. Unfortunately, there is no standard or portable way. (Some compilers provide nonstandard extensions.) If you need to know, you'll have to keep track of it yourself. (See also question 7.28.)

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345