In c, say you have the following structure and an instance of that:
#include <stdio.h>
#include <stdlib.h>
int main()
{
typedef struct _a {
int *a1;
float *a2;
char *a3;
}a;
a b;
b.a1 = (int *) malloc(sizeof(int) * 10);
b.a2 = (float *) malloc(sizeof(float) * 10);
b.a3 = (char *) malloc(sizeof(char) * 10);
return 0;
}
Now, how to find the total memory that is allocated/associated with the variable b? sizeof(b) will just return the combined size of the pointers in the structure but will not calculate the sum of the memories that has been allocated using malloc for different types/sizes. How to find the total size of this structure in the memory (including padding if applicable)?
You’ll have to keep track of the aggregate size of your structure yourself.
The C infrastructure doesn’t know what memory is allocated to which pointers.
Even creating a strong, generalized concept of “ownership” of memory by a pointer is exceedingly difficult.
To illustrate, realize that the elements of your structure could contain other pointers that reference other memory. Some of those references could be in loops (circularly linked list, undirected graphs).
In that case, counting the memory could become impossibly difficult. If two different elements point to the same memory, should it be counted twice, or once? What system would keep track of which memory is counted or not counted? How would that system fit into C’s minimalist paradigm?
To do what you’re asking, I think you need a language with reflection/introspection, such as Java or .Net (C#).