Suppose I have a struct with the following form
typedef struct A
{
double one;
double two;
void *some_ptr;
uint8_t *array_ptr;
}
This struct has size 32 Bytes on my system. I have a single uint8_t variable that I would like to add to this struct, however, memory is at a premium (there are going to be A LOT of these structs).
Therefore, the following is not something I would like to do because it would increase my memory usage to 40 Bytes.
typedef struct B
{
double one;
double two;
void *some_ptr;
uint8_t *array_ptr;
uint8_t my_value;
}
What I'm wondering is if I add an extra index to the array (all arrays will be the same size, however, I won't know the size until runtime) if instead I can reduce the amount of memory I'm using from 40 to 33 bytes (array will be allocated with malloc).
When malloc is called it should return an amount of memory equal to one page though I'm only guaranteed to have access to the amount of memory I request (please correct me if I'm wrong). With this in mind, my question can be boiled down to the following:
If I use malloc to allocate one extra byte for the array and store my variable at the end of the array instead of its own variable in the struct will I save memory? I ask this question because it's unclear to me how much memory malloc will actually allocate. For example, if I ask it to give me 10 bytes for one array, do I get ten bytes or 16 guaranteed (64 bit system)? If I ask it to give me 10 bytes twice for two arrays do I get 20 bytes, 32 bytes, or 24 (24 because the total has to be in chucks of 8 bytes)? Because malloc should return pointers that are multiples of 8 I believe the answer would be 32 but I'm not sure (if this is the case then in the worst case I would get the same memory usage as just adding a variable to the struct). Another way this question may be phrased is if I use malloc to allocate X bytes, how many bytes are actually used?
Note: Questions similar to the one I have, have been asked before but I don't believe they address the question that I'm actually asking. i.e.
https://stackoverflow.com/questions/5213356/malloc-how-much-memory-has-been-allocated
https://stackoverflow.com/questions/25712609/how-much-memory-does-calloc-actually-allocate