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 ?
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
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.
- windows https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/msize?view=msvc-170
- linux https://linux.die.net/man/3/malloc_usable_size
- mac https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/malloc_size.3.html#//apple_ref/doc/man/3/malloc_size