-1
int *zahl = malloc(sizeof(int)*4);

I am confused, I know the size of int is 4 bytes thus, 4 * 4 = 16. However, when I use printf(sizeof(zahl); it gives me 8. How can I solve it ?

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
Mimo
  • 7
  • 1
  • 7
    `sizeof(zahl)` = size of pointer, not the size of memory `zahl` is pointing to. – Gaurav Sehgal Mar 12 '22 at 17:06
  • If the allocation was successful, `malloc` returns a non-null pointer. You should check for null-ness after calling `malloc`. If non-null, then the size is whatever you requested. The exception is if you request 0, in which case the return value is implementation defined. – JohnFilleau Mar 12 '22 at 17:09
  • Mimo, best to post true code, unlike `printf(sizeof(zahl);`. – chux - Reinstate Monica Mar 12 '22 at 17:23

3 Answers3

1

So printf(sizeof(zahl)) is showing 8 because it is the size of integer pointer. sizeof basically returns the size of the variable or pointer which you pass in it's argument depending on it's datatype. In your case you have put zahl as an argument of sizeof, so it has returned the sizeof zahl which is an integer pointer. Any pointer in x64 compiler has a size of 8 bytes.

0

sizeof( zahl ) gives the size of the pointer (x64 = 8 bytes).

There is no way in standard C to find the amount of memory allocated from malloc.

However this answer determine the size of dynamically-allocated memory

Gives some solutions on popular platforms

mksteve
  • 12,614
  • 3
  • 28
  • 50
0

To extend the answers above: there is no way for you to discover the size of the memory allocated if all you have is the pointer.

The internals of the heap management system (the thing that does malloc and free) knows, but there is no standard way of asking for this information.

Eric pointed out the following (TY) non standard extensions.

pm100
  • 48,078
  • 23
  • 82
  • 145
  • Re “I have never met a heap with a 'getinfo' call, but I am sure they exist”: It is quite remarkable you have never met Microsoft Windows ([`_msize`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/msize?view=msvc-170)), Linux ([`malloc_usable_size`](https://linux.die.net/man/3/malloc_usable_size)), or macOS ([`malloc_size`](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/malloc_size.3.html#//apple_ref/doc/man/3/malloc_size)). – Eric Postpischil Mar 12 '22 at 17:39
  • @EricPostpischil - ok let me put it another way, "I am sure the many heap managers have non standard extensions to do this, but I have never had reason to need this info so have never investigated it". So I have not "knowingly" met them. TIL that they are there. TY – pm100 Mar 12 '22 at 17:44