-1

For example, you have the language c code:

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

for some reason, if i print the size of the pointer p, even though it has 8 bytes (as i allocated it with malloc) it shows 4 when i print it:

printf("%i", sizeof(p)); // results on 4

i know that the default size of an integer is 4, but i'm allocating more memory than that with malloc, i'm allocating 8 bytes and it's still printing 4 when i do sizeof, why is that happening?

  • Given `int *p = ...` and `sizeof(p)` is the size of a pointer. Why is 4 not reasonable for a pointer? If code was `int x = 42;`, would your expect `sizeof(x)` to be 4 or 42? – chux - Reinstate Monica Nov 20 '21 at 22:55
  • the size should be 8 because i allocated 8 for the pointer with malloc, and when i print it's not, it's 4, that's what i'm not understanding. – Synthy Jericho Nov 20 '21 at 22:57
  • 1
    `sizeof(p)` is the size of the object `p`, not its value from some assignment. `p` is a pointer, so its size here should be and is 4. – chux - Reinstate Monica Nov 20 '21 at 22:59
  • so how do i do to extract the size of object p? (which is 8) in code? – Synthy Jericho Nov 20 '21 at 23:07
  • If `malloc` returns a non-`NULL` pointer value, the size is `8`, the amount you requested in `malloc(8)`. So if you want to know the size, it comes from the same place that the `8` came from. – Weather Vane Nov 20 '21 at 23:12
  • *the size should be 8 because i allocated 8 for the pointer* No. You allocated 8 bytes for the memory *pointed to by* the pointer. – Steve Summit Nov 20 '21 at 23:40
  • "how do i do to extract the size of object p? (which is 8)", No, the object is a _pointer_. Its size is 4. Use `sizeof(p)` to get the size of the pointer `p`. To get the amount allocated, code knows it is 8 if `malloc()` returned non-`NULL`. Keep track of the 8. – chux - Reinstate Monica Nov 21 '21 at 00:57
  • To be clear the size of the pointer `p` is not related to anything assigned to it, including some allocation. A more reasonable question would be, "given the _value_ of an allocation, (return value from `malloc()`) how to find the amount of memory allocated? (There is no portable solution). – chux - Reinstate Monica Nov 21 '21 at 01:04

1 Answers1

2

Using the sizeof operator on a pointer will give you the size of the pointer itself, which is typically 4 bytes on 32-bit platforms and 8 bytes on 64-bit platforms.

Using the sizeof operator on a pointer will not give you any information about the size of the object that the pointer is pointing to. In particular, if the pointer is pointing to the result of a malloc allocation, it will not provide any information about the size of this allocation. You must keep track of the size of the allocation yourself, for example by storing it in a separate variable, because the C standard library does not provide any way of obtaining this information.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39