This question is inspired by Python
memory management techniques for variable storage. I want to implement a similar feature in C language.
Most of the variables in a large running program, in general, have values 0
and 1
. Suppose 100 variables of datatype int
are having values 0
or 1
, so we are using 100 * sizeof(int) = 400
bytes of memory. Instead, we can point each variable to following struct with a reference count, which reduces memory usage to only few bytes. The structure is de-allocated when the reference count reaches 0
.
struct var
{
int value;
int refCount;
}
What I want to achieve is that when I define several int
's, the Linked List would be as follows:
void foo()
{
int a = 0, b = 0, c = 0;
int i = 1, j = 1;
int x = 7;
int p = 5, q = 5;
}
results in following Linked List
[Head] <-> [0,3] <-> [1,2] <-> [7,1] <-> [5,2] <-> [Tail]
Here a
,b
and c
point to node [0,3]
. i
and j
point to node [1,2]
and so on. Now, how do I override memory allocation of variables in C
and implement my own algorithm to do so as above? Does C++
provide any such feature?
UPDATE: If we change a = 9
, then a new node is created as [9,1]
and previous node changed to [0,2]
. When reference count reaches 0
, it is de-allocated.