c - 在c中,有专门分配内存的函数是不是很糟糕?

标签 c memory memory-management

在 c 项目中,在函数内部分配内存时哪种策略最好
例如,我得到了这个结构:

  typedef struct t_example{
    int x;
    int y;
  }example;
  
我创建了一个初始化实例的函数:
  /**
   return value must be freed
   */
  example * example_init(){
    example *p_example = malloc(sizeof(example));
    p_example->x = 42;
    p_example->y = 42;
    return p_example;
  }
我可以这样调用这个函数
example *p_example = example_init();
但是随着项目的发展,我发现有时我不需要分配内存,如果我只需要堆栈上的一个局部变量,但需要对其进行初始化,所以我将 init 函数更改为:
  void example_init(example *p_example){
    p_example->x = 42;
    p_example->y = 42;
  }
所以我可以像这样调用这个函数
example o_example;
example_init(&o_example);
当然,如果我有一个指针,同样的功能也可以工作
example *p_example = malloc(sizeof(example));
example_init(p_example);
我的问题是:这是最佳做法:
  • 提供一个分配内存的函数(并正确记录这一点),因为它在某些情况下可能很方便,或者 2)这应该留给函数的调用者。

  • 我还读到 std 函数不会动态分配内存,这就是 strdup 函数不是标准的原因。所以我会说第二种选择是最好的?

    最佳答案

    My question is: which is the best practice : 1) to offer a function that will allocate memory (and properly document this) as it may be convenient in come cases, or 2) this should it be left to the caller of the function.



    我不认为这是最佳实践的问题。创建并返回(指向)一个新的、动态分配的对象的函数本身并没有错。为了比直接分配空间更有用,这样的函数也应该确保给对象一个一致的初始值,尽管它可以通过调用不同的函数来做到这一点。总的来说,这是 C++ 的 new 的 C 模拟。运算符与构造函数相结合。

    这并不排除用户自己分配对象的规定,无论是动态的还是其他的。如果所讨论的类型是公共(public)的,那么可能有充分的理由提供一个不进行分配的初始化函数。正如您所观察到的,这特别适用于依赖自动或静态分配对象的代码。

    I also read that the std function do not allocate memory dynamically, and that's why the strdup function is not standard. So I would say that the second option is the best ?



    标准委员会对标准库函数的政策不能合理地扩展到您自己的函数。最终的结果是,任何地方的函数都不应该动态分配内存,如果这是委员会的意图,那么他们至少会弃用标准库的显式内存分配函数。

    关于c - 在c中,有专门分配内存的函数是不是很糟糕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956665/

    相关文章:

    c - unistd write() 在连续 100 次套接字写入/读取后停止写入,程序返回 3328 错误代码

    c - 使用 typedef 结构从不兼容的指针类型赋值

    java - 了解 *nix 中的 RES 内存并调试内存泄漏

    c# - 制作一个shuffle方法

    linux - 缓冲区/缓存使用 100% 内存

    c - 防止内核代码中的双 kfree?

    c++ - 调用 new 时出现内存故障

    c - (const char *str) , (char const *str) 和 (char *const str) 之间有什么区别?

    c - C程序需要多少内存

    c - 无符号整数的大小为 8