c - 关于如何在 C 结构中表示缓冲区

标签 c struct

我最近看到以下类似结构可以包含有关缓冲区的信息。我知道“buffer”字段可能指向缓冲区的起始地址,所以我们可以使用memcpy(pDst, pEntry->buffer, bufferLen)来复制缓冲区到另一个地方(pDst),但是我们如何分配Entry

struct Entry
{
    // data fields.
    size_t bufferLen;
    unsigned char buffer[1];
};

最佳答案

这是旧的、C99 之前的“struct hack”示例,它在 C99 中被转换为“灵活数组成员”。假设你想存储一个字符串。您可以使用以下方式动态分配空间:

struct Entry *make_entry(const char *str)
{
    size_t  len = strlen(str) + 1;
    struct Entry *e = malloc(sizeof(struct Entry) + len);
    if (e != 0)
    {
        e->bufferLen = len;
        strcpy(e->buffer, str);
    }
    return e;
}

在 C99 中,您将编写相同的代码;但是,结构的声明会有所不同,因为您没有指定数组的大小:

struct Entry
{
    size_t bufferLen;
    unsigned char buffer[];
};

这会占用更少的空间,尤其是在 sizeof(size_t) == 8 的 64 位系统上。

此类结构存在主要限制(灵活的数组成员样式和结构 hack 样式),其中之一是您不能简单地分配结构。您必须允许额外的空间并使用 memmove()memcpy() 复制它。

struct Entry *dup_entry(const struct Entry *e)
{
    struct Entry *r = malloc(sizeof(struct Entry) + e->bufferLen);
    if (r != 0)
        memmove(r, e, sizeof(struct Entry) + e->bufferLen);
    return r;
}

您也不能创建此类结构的数组(但您可以创建指向此类结构的指针数组)。


I think in your make_entry() function, we can allocate one less memory as the Entry->buffer has already stored one char.

有趣的评论——而且是一种轻描淡写的说法。曾经有另一个答案(现已删除),它收集了一些有趣且恰当的评论,我将把这些评论纳入这个答案。

Michael Burr注意到:

memcpy(pDst, pEntry, offsetof(struct Entry, buffer[pEntry->bufferLen])) would be a safer idiom — if there happens to be more than one entry before the array hack at the end of the struct, you don't have to manually account for all of them, and it lets the compiler deal with any padding before the hack array automatically. Similarly, allocation of an instance can be: pEntry = malloc(offsetof(struct Entry, buffer[desiredVarArrayElements]))

这是一个有趣的观察结果,与您的建议非常吻合。 offsetof() 的使用导致不是编译时常量的结果;结果取决于在运行时用作下标的值。这是非正统的,但我看不出有什么不妥。对于用作下标的大小而言,在计数中包含空字节至关重要。

这也导致了一个有趣的观察,即如果将此技术用于短字符串,您最终可以为结构分配比 sizeof(struct Entry) 更少的字节。这是因为整个结构在大多数 32 位机器上是 4 字节对齐的,而在 sizeof(size_t) == 8 的大多数机器上是 8 字节对齐的(通常是 64 位 Unix 系统,但不是 64 位 Windows)。

因此,如果要分配的字符串只有 3 个字节(2 个字符和 1 个空终止符字节),则指定给 malloc() 的大小将为 7 或 11(在 32 位或分别为 64 位机器),与 8 或 16 的结构大小进行比较。

因此,我为“struct hack”结构编写的代码(如问题中所示)采用了(安全的)快捷方式并过度分配了所需的总内存,可能是 4 个字节或 8 个字节。有可能减少这种过度分配。请注意,内存分配器本身通常会分配一个向上舍入的大小——在 32 位系统上通常(但不一定)是 8 字节的倍数,在 64 位系统上通常是 16 字节的倍数。这意味着尝试分配更少的字节可能不会像您预期的那样带来好处(尽管有时会带来一些好处)。

请注意,C99 灵活数组成员根本不会产生任何空间浪费;结构的大小根本不包括灵活的数组成员。这使得它比 struct hack 更容易使用;您不必以同样的方式担心浪费空间。

Steve Jessop注意到:

If you're making such structs copyable, then in any case you should probably have a capacity as well as a size field in the struct. Then write a function to copy them which checks the capacity, copies the size (but not the capacity), and copies the data. If you do those three things separately then you don't have to worry about layout. And since there are are so many things to do, users of the struct shouldn't try to copy it themselves, they should use the function.

当然,这正是我定义 dup_entry() 的原因;确实有必要防止人们在复制时出洋相。 make_entry()dup_entry() 函数的实现必须相互一致,但这并不难。

关于c - 关于如何在 C 结构中表示缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471458/

相关文章:

c - 向后打印双向链表段错误

c++ - 链表实现链表

go - 创建包含指针的 Go 结构的可重复字节数组

c - 将 GStreamer 添加到 Eclipse

c - 编写原子函数

c++ - 具有动态分配成员的结构 vector

c - 列表C中字符串的动态内存分配

go - golang类型[] dao.Record没有字段或方法ID

c - 使用引用调用打印数组元素

c - 使用指针获取结构中动态int数组的值