一次分配指针和指针 [英] Allocate Pointer and pointee at once

查看:92
本文介绍了一次分配指针和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想减少 malloc() s(特别是如果数据较小且经常分配),我想立即分配指针和指针。

If I want to reduce malloc()s (espacially if the data is small and allocated often) I would like to allocate the pointer and pointee at once.

如果您假设以下内容:

struct entry {
    size_t      buf_len;
    char        *buf;
    int         something;
};

我想以以下方式分配内存(不在乎此处的错误检查):

I would like to allocate memory in the following way (don't care about error checking here):

size_t buf_len  = 4;                // size of the buffer
struct entry *e = NULL;

e = malloc( sizeof(*e) + buf_len ); // allocate struct and buffer
e->buf_len  = buf_len;              // set buffer size
e->buf      = e + 1;       // the buffer lies behind the struct



这甚至可以扩展,以便分配整个数组

This could even be extende, so that a whole array is allocated at once.

您如何评估以下方面的技术?

How would you assess such a technuique with regard to:


  • 可移植性

  • 可维护性/扩展性

  • 性能

  • 可读性

  • Portability
  • Maintainability / Extendability
  • Performance
  • Readability

这合理吗?如果可以使用,是否有任何关于如何为此设计接口的想法?

Is this reasonable? If it is ok to use, are there any ideas on how to design a possible interface for that?

推荐答案

您可以使用灵活的数组成员而不是指针:

You could use a flexible array member instead of a pointer:

struct entry {
    size_t      buf_len;
    int         something;
    char        buf[];
};

// ...
struct entry *e = malloc(sizeof *e  + buf_len);
e->buf_len = buf_len;

可移植性和性能都很好。可读性:不够完美,但足够好。

Portability and performance are fine. Readability: not perfect but good enough.

可扩展性:您一次只能使用一个以上的成员,因此必须使用显式指针版本。此外,显式指针版本意味着,如果将其与不具有 1 对齐方式的类型一起使用,则必须进行乱码操作以确保正确的对齐方式。

Extendability: you can't use this for more than one member at a time, you'd have to fall back to your explicit pointer version. Also, the explicit pointer version means that you have to muck around to ensure correct alignment if you use it with a type that doesn't have an alignment of 1.

如果您正在认真考虑这一点,我会考虑重新访问整个数据结构的设计,以查看是否还有另一种方法。 (也许这种方法实际上是最好的方法,但是请先仔细考虑一下。)

If you are seriously thinking about this I'd consider revisiting your entire data structure's design to see if there is another way of doing it. (Maybe this way is actually the best way, but have a good think about it first).

这篇关于一次分配指针和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆