如何设置 4 字节长的底部 3 个字节,同时保持顶部字节不变?
相关代码是这样的:
typedef unsigned long int chunk_head;
typedef struct malloc_chunk
{
// Contains the size of the data in the chunk and the flag byte.
chunk_head head;
// Deliberately left unsized to allow overflow.
// Contains the payload of the chunk.
unsigned int data[];
};
作为一个例子,“get”宏是这样的:
//Get the size of the data contained within the chunk.
#define GET_CHUNK_SIZE(chunk) ((chunk.head) & 0xFFFFFF)
我使用标志位的高位字节——“inuse”和“can be coalesced”,以及我发现的任何其他位有用的。
现在我已经提供了背景信息,正如我在标题中所述,我需要能够将较低的 3 个字节更改为块的大小。我最初的本能是按位与标头与大小,因为它会正确对齐,但后来我意识到它也可能会覆盖标志字节,因为它会自动在前面添加零,直到它的大小与长匹配。我什至不确定您是否可以按位与 int 和 long。不管怎样,非常感谢帮助。
Relevant code is this:
typedef unsigned long int chunk_head;
typedef struct malloc_chunk
{
// Contains the size of the data in the chunk and the flag byte.
chunk_head head;
// Deliberately left unsized to allow overflow.
// Contains the payload of the chunk.
unsigned int data[];
};
And just as an example, the "get" macro is this:
//Get the size of the data contained within the chunk.
#define GET_CHUNK_SIZE(chunk) ((chunk.head) & 0xFFFFFF)
The upper byte I'm using the bits for flags -- "inuse" and "can be coalesced", and any additional ones that I find will be useful.
Now that I'm done providing background information, as I stated in the title, I need to be able to change the lower 3 bytes to how large the chunk is. My initial instinct was to bitwise AND the header with the size, since it would be properly aligned, but then I realized it might overwrite the flag bytes too, because it automatically prepended zeroes until it size matched the long. I'm not even sure you can bitwise AND an int and a long. Anyway, help greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
怎么样:
How about:
由于某种原因,到目前为止,您收到的大多数回复都坚持将潜在的大小溢出问题掩盖起来,即它们将块大小与
0x00FFFFFF
进行“和”,从而悄悄地丢弃过多的大小位(如果有) ),然后继续将大小的完全无意义的尾部部分写入该字段。我不知道为什么有人会做这样的事情。更合理的代码可能如下所示
没有有效的理由将大小与
0x00FFFFFF
进行“和”。您应该中止或至少断言过多的大小,而不是悄悄丢弃多余的内容。For some reason most of the responses you received so far insist on sweeping the potential size overflow issue under the carpet, i.e. they "and" the chunk size with
0x00FFFFFF
thus quietly discarding the excessive size bits (if any) and then proceed to write the completely meaningless tail portion of the size into the field. I don't know why would anyone do something like that.The more reasonable code might look as follows
There is no valid reason to "and" the size with
0x00FFFFFF
. You should either abort or at least assert on excessive size, not quietly discard the excess.使用位字段来执行此操作。它避免了必须使用宏,在调试器中也很好:
Use bit fields to do this. It avoids having to use the macros, nice in the debugger too:
chunk.head = (chunk.head & ~0xffffffL) |
chunk.head = (chunk.head & ~0xffffffL) | (new_lower_bits)
chunk.head = (chunk.head & ~0xffffffL) | (new_lower_bits)
这是你的意思还是我错过了什么?
Is that what you meant or did I miss something?