Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc_usable_size() returns the wrong size

Tags:

c

memory

malloc

I want to know the size allocated by malloc.
I have written the source code below.

test.c

#include <stdio.h>
#include <stdint.h>
#include <malloc.h>
void main(void)
{
    uint8_t *test;

    test = (uint8_t *)malloc(sizeof(uint8_t)*4);
    printf("sizeof(test) = %d\n",malloc_usable_size(test));

    free(test); 
}  

I expected size to be 4.
But the result is 12.

sizeof(test) = 12

Can you tell me what's wrong?
I hope that size 4 correctly comes out.

like image 269
DonBit Avatar asked Oct 20 '25 15:10

DonBit


1 Answers

malloc_usable_size(test)

The value returned by above function is not fixed as you requested. it may be greater than the requested size of the allocation depending upon the cpu byte ordering and alignment. this is totally depend upon the underlaying implementation.

like image 177
suraj Avatar answered Oct 23 '25 04:10

suraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!