1

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.

manav m-n
  • 11,136
  • 23
  • 74
  • 97

2 Answers2

0

You will have to implement this yourself, and it's not going to be transparent. Your variables won't be ints any more, but rather pointers to something or other.

Also, note that in your example, if you change a, b and c will also be changed.

zmbq
  • 38,013
  • 14
  • 101
  • 171
0

Either you don't know the nature of the data, then you have to make an algorithm that allocates the data dynamically in a specific manner, as you describe.

Or you know the nature of the data at compile time, and then you can decide to allocate it in the manner you prefer. It doesn't make any sense to "override the way C allocates variables", since it doesn't make sense to have the program, in runtime, calculate what allocations that were needed for itself at compile time.

The best way to achieve this is perhaps to have a script that generates the C code.

Lundin
  • 195,001
  • 40
  • 254
  • 396