简体   繁体   English

设计用于可变存储的内存块

[英]Designing Memory block for variable storage

This question is inspired by Python memory management techniques for variable storage. 这个问题的灵感来自于用于变量存储的Python内存管理技术。 I want to implement a similar feature in C language. 我想用C语言实现类似的功能。

Most of the variables in a large running program, in general, have values 0 and 1 . 通常,大型运行程序中的大多数变量的值均为01 Suppose 100 variables of datatype int are having values 0 or 1 , so we are using 100 * sizeof(int) = 400 bytes of memory. 假设数据类型为int 100个变量的值为01 ,那么我们使用100 * sizeof(int) = 400字节的内存。 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 . 当引用计数达到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: 我要实现的是,当我定义多个int ,链接列表将如下所示:

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] . 这里abc指向节点[0,3] i and j point to node [1,2] and so on. ij指向节点[1,2] ,依此类推。 Now, how do I override memory allocation of variables in C and implement my own algorithm to do so as above? 现在,如何在C 覆盖变量的内存分配并实现自己的算法来实现上述目的? Does C++ provide any such feature? C++是否提供任何此类功能?

UPDATE : If we change a = 9 , then a new node is created as [9,1] and previous node changed to [0,2] . 更新 :如果我们更改a = 9 ,那么将创建一个新节点,其名称为[9,1]而先前的节点更改为[0,2] When reference count reaches 0 , it is de-allocated. 当引用计数达到0 ,将对其进行取消分配。

You will have to implement this yourself, and it's not going to be transparent. 您将必须自己实现它,并且它不会透明。 Your variables won't be int s any more, but rather pointers to something or other. 您的变量不再是int了,而是指向某个东西或其他东西的指针。

Also, note that in your example, if you change a , b and c will also be changed. 另外,请注意,在您的示例中,如果更改a ,则bc也将更改。

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. “覆盖C分配变量的方式”没有任何意义,因为让程序在运行时计算在编译时自身需要什么分配是没有意义的。

The best way to achieve this is perhaps to have a script that generates the C code. 实现此目的的最佳方法可能是拥有一个生成C代码的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM