简体   繁体   English

当我们在 c 中有更简单的代码时,为什么要使用 malloc 或 calloc?

[英]Why do we use malloc or calloc when we have a simpler code in c?

#include <stdio.h>

int main() {
    int n = 0, i;
    printf("Enter the size of array\n");
    scanf("%d", &n);
    int a[n];
    for (i = 0; i < n; i++) {
        a[i] = i + 1;
        printf("%d,", a[i]);
    }
}

May I know the difference between malloc() and calloc() and this code, because I guess both are fulfilling the need?我可以知道malloc()calloc()之间的区别以及这段代码,因为我猜两者都满足了需求?

Note that as per the latest standard, VLAs are not mandatory part of the spec.请注意,根据最新标准,VLA 不是规范的强制性部分。 Allocator functions ( malloc() and family) are the standard way of allocating memory for which size is only known at run-time.分配器函数( malloc()和 family)是分配内存的标准方法,其大小仅在运行时才知道。

Quoting C18 , chapter 6.7.6.2/P4引用C18 ,第 6.7.6.2/P4 章

[...] (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.) [...](可变长度数组是实现不需要支持的条件特性;参见 6.10.8.3。)

That said, there are other usage limitations in case of VLAs due to their nature, their lifetime is limited in the scope in which they are defined.也就是说,由于 VLA 的性质,在 VLA 的情况下还有其他使用限制,它们的生命周期在定义的范围内受到限制。 For example, you cannot return a VLA, defined in a function from a function call, but if you use allocator functions, you can return the pointer, as it's lifetime remains until programatically released (call free() ).例如,您不能从函数调用返回在函数中定义的 VLA,但如果您使用分配器函数,则可以返回指针,因为它的生命周期一直保持到以编程方式释放(调用free() )。

The line线

int a[n];

declares a as a variable-length array . a a 声明为可变长度数组 VLAs are useful, but limited: VLA 很有用,但有局限性:

  • They cannot be declared with the static keyword or at file scope;它们不能用static关键字或在文件范围内声明;
  • They cannot be initialized in the declaration - eg, you can't write something like int a[n] = {0};它们不能在声明中初始化——例如,你不能写类似int a[n] = {0}; ; ;
  • They cannot be members of a struct or union type;它们不能是structunion类型的成员;
  • They cannot be arbitrarily large;它们不能任意大;
  • They are not universally supported - they were introduced in the 1999 revision of the language definition and made optional in the 2011 revision;它们并未得到普遍支持——它们是在 1999 年的语言定义修订版中引入的,并在 2011 年的修订版中成为可选的;
  • They cannot be resized after they are defined - the "variable" in variable-length only means that their size isn't fixed from one definition to the next.它们在定义后无法调整大小 - 可变长度中的“变量”仅意味着它们的大小从一个定义到下一个定义都不是固定的。

Like any auto variable, they cease to exist when you exit their enclosing scope.与任何auto变量一样,当您退出其封闭范围时,它们将不复存在。

Dynamically-allocated memory has a few advantages over VLAs:动态分配的内存比 VLA 有几个优点:

  • The memory stays allocated until you explicitly free it;内存保持分配状态,直到您明确free它;
  • You can allocate an arbitrarily large block of memory;您可以分配任意大的内存块;
  • You can resize the allocated block as necessary;您可以根据需要调整分配块的大小;
  • Unlike VLAs, malloc , calloc , and realloc are supported by any hosted implementation;与 VLA 不同,任何托管实现都支持malloccallocrealloc

If all you need is some temporary working storage within a function, you don't know its size ahead of time, you don't need too much of it, and they are supported, then VLAs are a good option and less messy than using malloc or calloc .如果你只需要一个函数中的一些临时工作存储,你不知道它的大小,你不需要太多,并且它们是受支持的,那么 VLA 是一个不错的选择,并且比使用更简洁malloccalloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我们需要calloc(或malloc)? - Why do we need calloc (or malloc)? 当我们尝试在C编程中将malloc用于多个字符串时,为什么malloc有效但calloc不起作用? - Why does malloc works but calloc doesn't when we try to use it for multiple strings in C programming? 我们必须malloc一个结构吗? - Do we have to malloc a struct? 为什么我们需要在 C 中为数组使用 malloc() 或任何其他动态内存? - Why do we need to use malloc() or any other Dynamic Memory for ARRAYS in C? 为什么我们在实现对齐的 malloc 时使用按位运算符 &amp; 和 ~ 而不是数学运算符 %? - Why do we use bitwise operators & and ~ instead of mathematical operators % when implementing aligned malloc? 为什么我们在插入节点时在链表中使用malloc? - Why do we use malloc in linkedlist while inserting a node? 为什么在C中读取文件时,我们必须使用字符数组? - Why in C, when reading files, do we have to use a character array? 使用CUDA时,为什么malloc()和calloc()似乎不起作用? - Why do malloc() and calloc() not seem work when using CUDA? 我们什么时候需要使用posix_memalign而不是malloc? - When do we need to use posix_memalign instead of malloc? 当我们malloc()时,我们真的必须要free()吗? 那有什么和自动变量不同呢? - Do we really have to free() when we malloc()? What makes it different from an automatic variable then?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM