C 中 malloc 的惯用宏?

Idiomatic macros for malloc in C?

背景

在与 C++ 一起为高级项目工作一段时间后,我正在学习低级开发。目前正在摸索典型的 C 模式,并在 linux 内核和旧电子邮件中跌跌撞撞。

问题

是否有一组通常used/idiomatic宏,或通用函数来减少内存分配中的重复或错误?

我在我的代码中经常看到的是 malloc 中的长乘法语句,我认为它很乏味,而且是出现问题的好地方。 示例:

struct my_struct {
    size_t size;
    char* memory;
}

struct my_struct* my_struct_new(size_t size) {
    struct my_struct* ms = malloc(sizeof *ms)
    
    ms->size = size;
    ms->memory = malloc(size * sizeof *ms->memory);

    return ms;
}

我试图通过在这里进行错误尝试来避免产生 XY 问题。

感谢您的宝贵时间。

不,这几乎是在 C 语言中分配内存的惯用方式。*alloc 函数不知道也不关心类型,它们只关心你想要多少字节。获得该数字的最佳方法(无论如何,除了字符串或字节缓冲区之外)是将目标的大小 (sizeof *ms->memory) 乘以你想要的元素数 (size)。否则你可以使用 calloc 将这些东西作为单独的参数传递,但是 calloc 将零初始化内存,这可能是也可能不是你想要的。

您可以而且应该将复杂的分配抽象到它们自己的函数中(就像这个片段所做的那样)。但就任何现有的便利宏而言 - 并非如此。

Are there a set of commonly used/idiomatic macros, or generic functions which reduce repetition or reduce mistakes in memory allocation?

不完全是, 大部分都涵盖了。

struct my_struct 创建一个分配器函数 - 在 C 语言中非常地道。

实现中的一个小弱点是缺乏检查内存不足的功能——这是健壮代码所期望的。

struct my_struct* my_struct_new(size_t size) {
    struct my_struct *ms = malloc(sizeof *ms)
    if (ms) {
      ms->size = size;
      ms->memory = malloc(size * sizeof *ms->memory);
      if (ms->memory == NULL) {
        free(ms);
        ms = NULL;
      }
    }
    return ms;
}

还研究Flexible array member

struct my_struct_fma {
    size_t size;
    char memory[];
}

struct my_struct_fma *my_struct_new_fma(size_t size) {
    struct my_struct_fma *ms = malloc(sizeof *ms + sizeof *ms->memory * size);
    if (ms) {
      ms->size = size;
      }
    }
    return ms;
}