There is a creation of a global accessible structure as:
struct dummy1 {
int data1;
int data2[10];
} DATA_STORE_A;
struct dummy2 {
int data1;
int data2[10];
int extended_data[20];
} DATA_STORE_B;
struct sample {
int one_value;
int value_array[30];
void *dynamic_data;
} SAMPLE_STORE; // Global accessible structure
SAMPLE_STORE user_init(SAMPLE_STORE sample_instance_one, bool flag, int size) {
if (flag) {
} else {
sample_instance_one.dynamic_data = malloc(sizeof(DATA_STORE_B) * size);
}
return sample_instance_one;
}
Use case would be to read the correct size of dynamic_data member from structure SAMPLE_STORE
Current approach is:
int main() {
// Write C code here
SAMPLE_STORE sample_instance_one;
bool flag = true;
uint8_t size = 10;
printf("Size of sample_instance_one: %lu bytes\n", sizeof(sample_instance_one));
printf("Size of SAMPLE_STORE: %lu bytes\n", sizeof(SAMPLE_STORE));
printf("Size of DATA_STORE_A: %lu bytes\n", sizeof(DATA_STORE_A));
printf("Size of DATA_STORE_B: %lu bytes\n", sizeof(DATA_STORE_B));
if (flag) {
sample_instance_one.dynamic_data = malloc(sizeof(DATA_STORE_A) * size);
printf("Size of DATA_STORE_A(sample_instance_one.dynamic_data): %lu bytes\n", sizeof((DATA_STORE_A*)sample_instance_one.dynamic_data));
} else {
sample_instance_one.dynamic_data = malloc(sizeof(DATA_STORE_B) * size);
printf("Size of DATA_STORE_B(sample_instance_one.dynamic_data): %lu bytes\n", sizeof((DATA_STORE_B*)sample_instance_one.dynamic_data));
}
return 0;
}
However, in this case the drawbacks are:
- VOID pointer has to be typecaster to appropriate structure, and for any other module process it may not be known value.
- Even though being (1) in to consideration at conditionally, another problem is with the sizeof return size is 8 bytes instead of actual size allocated by malloc function.
How can a program retrive actual consumed/allocated size?
sizeof((DATA_STORE_A*)sample_instance_one.dynamic_data) or sizeof(sample_instance_one.dynamic_data) does not return the actual size of allocated memory