为我的自定义malloc实现创建一个标志。

huangapple go评论68阅读模式
英文:

Create a flag for my own malloc implementation

问题

所以正如我在标题中所说,我目前正在开发自己的动态内存分配系统实现。

问题是,因为我希望实现尽可能简化,要在内存中有一个特定的“标志”,指示后面的内存已被占用(以及其大小)。

我想象中内存中的情况应该是这样的:...... | 标志 | 大小 | (数组的起始) | ......

我考虑使用一个大值,比如SIZE_MAX,因为从技术上讲,它在内存中看起来像是64个连续的1,我认为在内存中找到这种情况并不常见,但这也不是不可能的,因此这种技巧可能会出错...

有没有更安全的方法来做到这一点,创建一个机器永远不会通过任何手段创建的值?

提前感谢!

英文:

So as I said in the title, I'm currently working on my own implementation of a dynamic memory allocation system.

The problem is, because i want the implementation to be as minimal as possible, to have a certain "flag" in memory which would indicate that the memory after is taken (+ his size)

I imagine a thing like this in memory : ...... | flag | size | (start_of_array) | ......

I think of using a big value like SIZE_MAX because it would technically look like 64 ones aligned in the memory and i don't think it is really common in memory to find this BUT it's not improbable thus this technic is error prone...

Is there a safer way to do this and create a value that will never be created by the machine by any mean ?

Thanks in advance !

答案1

得分: 0

没有,没有任何值可以安全地假定不会被机器以任何方式放入内存中,除非是由您的分配器分配的。就SIZE_MAX而言,它是一个特别糟糕的选择。它本身有多个合理的用途,并且在相应的有符号整数类型中与-1具有相同的表示,而这个类型本身也有多个用途。

您不应该需要使用特殊值来识别您的内存块。通常,您会从一个或少数几个大的连续区域中分配内存。分配元数据可以单独保存,但分配器将元数据放在相同的空间中,类似于您描述的情况并不少见。在这种情况下,您只需要知道第一个块的位置。伴随该块的元数据,特别是记录的大小,告诉您如何找到下一个块(以及是否有下一个块),从而告诉您如何找到下一个,等等

英文:

> Is there a safer way to do this and create a value that will never be created by the machine by any mean ?

No, there is no value that you can safely assume would not be placed in memory other than by your allocator. And for what it's worth, SIZE_MAX is a particularly bad choice. It has multiple plausible uses itself, and it also has the same representation as -1 in the corresponding signed integer type, which has several uses of its own.

You should not need to use a special value to recognize your memory blocks. You would typically allocate memory out of one or a small number of large, contiguous regions. Allocation metadata can be kept separately, but it's not uncommon for allocators to put metadata in the same space, similar to what you describe. All you need in that case is the location of the first block. The metadata accompanying that block, especially its recorded size, tells you how to find the next block (and whether there is one), and that tells you how to find the next, etc..

huangapple
  • 本文由 发表于 2023年5月26日 08:52:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定