C语言 我对 C 上的 malloc() 和 calloc() 很困惑

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4237896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:08:30  来源:igfitidea点击:

I'm very confused about malloc() and calloc() on C

carraysmalloccalloc

提问by bluehallu

I've always programmed in Java, which is probably why I'm so confused about this:

我一直用 Java 编程,这可能是我对此如此困惑的原因:

In Java I declare a pointer:

在 Java 中,我声明了一个指针:

int[] array

and initialize it or assign it some memory:

并初始化它或为其分配一些内存:

int[] array = {0,1,0}
int[] array = new int[3]

Now, in C, it's all so confusing. At first I thought it was as easy as declaring it:

现在,在 C 中,这一切都令人困惑。一开始我以为声明就这么简单:

int array[]

and initializing it or assigning it some memory:

并初始化它或为其分配一些内存:

int array[] = {0,1,0}
int array[] = malloc(3*sizeof(int))
int array[] = calloc(3,sizeof(int))

Unless I'm wrong, all of the above is equivalent Java-C, right?

除非我错了,否则以上所有内容都等效于 Java-C,对吗?

Then, today I met a code in which I found the following:

然后,今天我遇到了一个代码,在其中我发现了以下内容:

pthread_t tid[MAX_OPS];

and some lines below, without any kind of initialization...

和下面的一些行,没有任何类型的初始化......

pthread_create(&tid[0],NULL,mou_usuari,(void *) 0);

Surprisingly (at least to me), the code works! At least in Java, that would return a nice "NullPointerException"!

令人惊讶的是(至少对我而言),代码有效!至少在 Java 中,这会返回一个不错的“NullPointerException”!

So, in order:

所以,按顺序:

  1. Am I correct with all of the Java-C "translations"?

  2. Why does that code work?

  3. Is there any difference between using malloc(n*sizeof(int))and calloc(n,sizeof(int))?

  1. 我对所有 Java-C“翻译”都正确吗?

  2. 为什么该代码有效?

  3. usingmalloc(n*sizeof(int))和之间有什么区别calloc(n,sizeof(int))吗?

Thanks in advance

提前致谢

回答by eq-

You can't assign memory to an array. An array has a fixed size, for the whole of its lifespan. An array can never be null. An array is not a pointer.

您不能为数组分配内存。数组在其整个生命周期内具有固定大小。数组永远不能为空。数组不是指针。

mallocreturns the address to a memory block that is reserved for the program. You can't "assign" that (being the memory block) to an array, but you can store the address of this memory block in a pointer: luckily, array subscription is defined through pointers - so you can "use pointers like arrays", e.g.

malloc将地址返回到为程序保留的内存块。您不能将其(即内存块)“分配”给数组,但您可以将此内存块的地址存储在指针中:幸运的是,数组订阅是通过指针定义的 - 因此您可以“使用像数组一样的指针” ,例如

int *ptr = malloc(5 * sizeof *ptr);
ptr[2] = 5; // access the third element "of ptr"
free(ptr); // always free at the end

When you declare an array without a size (i.e. array[]), it simply means the size of the array is determined from the initializer list. That is

当您声明一个没有大小的数组(即array[])时,它仅表示数组的大小由初始化列表确定。那是

int array[] = {1, 2, 3, 4, 5}; // is equal to
int array[5] = {1, 2, 3, 4, 5};

Trying to declare an array without a size and without an initializer is an error.

试图声明一个没有大小和初始化程序的数组是一个错误。



The code pthread_t tid[MAX_OPS];declares an array named tidof type pthread_tand of size MAX_OPS.

该代码pthread_t tid[MAX_OPS];声明了一个名为tidtypepthread_t和 size的数组MAX_OPS

If the array has automatic storage (i.e. declaration is inside a function and not static, not global), then each of the arrays elements has indeterminate value (and it would cause undefined behavior trying to read such value). Luckily, all that the function call does is that it takes the address of the first element of the array as the first parameter, and probably initializes it (the element) inside the function.

如果数组有自动存储(即声明在函数内部而不是静态的,不是全局的),那么每个数组元素都有不确定的值(并且会导致尝试读取此类值的未定义行为)。幸运的是,函数调用所做的只是将数组的第一个元素的地址作为第一个参数,并可能在函数内部初始化它(元素)。



The difference of callocand mallocis that the memory block that callocreturns is initialized to zero. That is;

的差callocmalloc是内存块calloc返回初始化为零。那是;

int *ptr = calloc(5, sizeof *ptr);
// is somewhat equal to
int *ptr = malloc(5 * sizeof *ptr);
memset(ptr, 0, 5 * sizeof *ptr);

The difference between

和...之间的不同

int *ptr = malloc(5 * sizeof *ptr);
// and
int array[5];

is that arrayhas automatic storage, (is stored on stack), and is "released" after it goes out of scope. ptr, however, (is stored on heap), is dynamically allocated and must be freed by the programmer.

array具有自动存储,(存储在堆栈中),并在超出范围后“释放”。ptr但是,(存储在堆上)是动态分配的,必须free由程序员进行分配。

回答by lornova

You are missing three very basic and tighten (and misleading!) C topics:

你错过了三个非常基本的和紧缩(和误导!)C 主题:

  • the difference between array and pointers
  • the difference between static and dynamic allocation
  • the difference from declaring variables on the stack or on the heap
  • 数组和指针的区别
  • 静态分配和动态分配的区别
  • 与在堆栈或堆上声明变量的区别

If you write int array[] = malloc(3*sizeof(int));you would get a compilation error (something like 'identifier' : array initialization needs curly braces).

如果你写int array[] = malloc(3*sizeof(int));你会得到一个编译错误(类似于“标识符”:数组初始化需要花括号)。

This means that declaring an array allows only static initialization:

这意味着声明一个数组只允许静态初始化:

  • int array[] = {1,2,3};that reserves 3 contiguous integers on the stack;
  • int array[3] = {1,2,3};which is the same as the previous one;
  • int array[3];that still reserves 3 contiguous integers on the stack, but does not initialize them (the content will be random garbage)
  • int array[4] = {1,2,3};when the initializer list doesn't initialize all the elements, the rest are set to 0 (C99 §6.7.8/19): in this case you'll get 1,2,3,0
  • int array[] = {1,2,3};在堆栈上保留 3 个连续的整数;
  • int array[3] = {1,2,3};与上一个相同;
  • int array[3];仍然在堆栈上保留 3 个连续整数,但不初始化它们(内容将是随机垃圾)
  • int array[4] = {1,2,3};当初始化列表未初始化所有元素时,其余元素设置为 0(C99 §6.7.8/19):在这种情况下,您将得到 1,2,3,0

Note that in all these cases you are not allocatingnew memory, you are just using the memory already committed to the stack. You would run in a problem only if the stack is full (guess it, it would be a stack overflow). For this reason declaring int array[];would be wrong and meaningless.

请注意,在所有这些情况下,您并没有分配新内存,您只是在使用已经提交给堆栈的内存。只有当堆栈已满时,您才会遇到问题(猜猜看,这将是堆栈溢出)。因此,声明int array[];将是错误且毫无意义的。

To use mallocyou have to declare a pointer: int* array.

要使用,malloc您必须声明一个指针:int* array.

When you write int* array = malloc(3*sizeof(int));you are actually doing three operations:

当你写的时候,int* array = malloc(3*sizeof(int));你实际上在做三个操作:

  1. int* arraytells the compiler to reserve a pointer on the stack (an integer variable that contains a memory address)
  2. malloc(3*sizeof(int))allocates on the heap 3 contiguous integers and returns the address of the first one
  3. =assigns copies that return value (the address of the first integer you have allocated) to your pointer variable
  1. int* array告诉编译器在堆栈上保留一个指针(一个包含内存地址的整数变量)
  2. malloc(3*sizeof(int))在堆上分配 3 个连续整数并返回第一个的地址
  3. =将返回值(您分配的第一个整数的地址)的副本分配给您的指针变量

So, to come back to your question:

所以,回到你的问题:

pthread_t tid[MAX_OPS];

is an array on the stack, so it doesn't need to be allocated (if MAX_OPSis, say, 16 then on the stack will be reserved the number of contiguous bytes needed to fit 16 pthread_t). The content of this memory will be garbage (stack variables are not initialized to zero), but pthread_createreturns a value in its first parameter (a pointer to a pthread_tvariable) and disregards any previous content, so the code is just fine.

是堆栈上的一个数组,因此不需要分配它(如果MAX_OPS是 16,那么堆栈上将保留适合 16 个 pthread_t 所需的连续字节数)。该内存的内容将是垃圾(堆栈变量未初始化为零),但pthread_create在其第一个参数(指向pthread_t变量的指针)中返回一个值并忽略任何先前的内容,因此代码很好。

回答by Puppy

C offers static memory allocation as well as dynamic- you can allocate arrays off the stack or in executable memory (managed by the compiler). This is just the same as how in Java, you can allocate an int on the stack or an Integer on the heap. Arrays in C are just like any other stack variable- they go out of scope, etc. In C99 they can also have a variable size, although they cannot be resized.

C 提供静态内存分配和动态内存分配 - 您可以在堆栈外或在可执行内存(由编译器管理)中分配数组。这就像在 Java 中一样,您可以在堆栈上分配一个 int 或在堆上分配一个整数。C 中的数组就像任何其他堆栈变量一样 - 它们超出范围等。在 C99 中,它们也可以具有可变大小,尽管它们不能调整大小。

The main difference between {} and malloc/calloc is that {} arrays are statically allocated (don't need freeing) and automatically initialized for you, whereas malloc/calloc arrays must be freed explicitly and you have to initialize them explicitly. But of course, malloc/calloc arrays don't go out of scope and you can (sometimes) realloc() them.

{} 和 malloc/calloc 之间的主要区别在于 {} 数组是静态分配的(不需要释放)并自动为您初始化,而 malloc/calloc 数组必须显式释放并且您必须显式初始化它们。但是当然, malloc/calloc 数组不会超出范围,您可以(有时) realloc() 它们。

回答by remy_jourde

2 - This array declaration is static :

2 - 这个数组声明是静态的:

pthread_t tid[MAX_OPS];

We don't need to allocate memory block, instead of dynamic allocation :

我们不需要分配内存块,而不是动态分配:

pthread_t *tid = (pthread_t *)malloc( MAX_OPS * sizeof(pthread_t) );

Don't forget to free the memory :

不要忘记释放内存:

free(tid);

3 - The difference between malloc and calloc is calloc allocate a block of memory for an array and initializes all its bits at 0.

3 - malloc 和 calloc 之间的区别在于 calloc 为数组分配一块内存并将其所有位初始化为 0。

回答by vy32

I find it helpful when you are programming in C (as opposed to C++) to indicate *array explicitly, to remember that there is a pointer that can be moved around. So I would like to start by rephrasing your example as:

我发现当您使用 C(而不是 C++)编程时,明确指示 *array 会很有帮助,记住有一个可以移动的指针。因此,我想首先将您的示例改写为:

int array[] = {0,1,2};
int *array = malloc(3*sizeof(int));
int *array = calloc(3,sizeof(int));

The first makes it clear that there is something called array which is pointing to a block of memory that contains a 0, 1 and 2. array can't be moved elesewhere.

第一个清楚地表明有一个叫做数组的东西,它指向一个包含 0、1 和 2 的内存块。数组不能移到别处。

Your next code: pthread_t tid[MAX_OPS];

你的下一个代码:pthread_t tid[MAX_OPS];

Does in fact cause an array with sizeof(pthread_t) * MAX_OPS to be allocated. But it does not allocate a pointer called *tid. There is an address of the base of the array, but you can't move it elsewhere.

实际上会导致分配 sizeof(pthread_t) * MAX_OPS 的数组。但它没有分配一个名为 *tid 的指针。有一个数组基址的地址,但你不能把它移到别处。

The ptherad_t type is actually a cover for a pointer. So tidabove is actually an array of pointers. And they are all statically allocated but they are not initialized.

ptherad_t 类型实际上是一个指针的覆盖。所以tid上面实际上是一个指针数组。它们都是静态分配的,但没有初始化。

The pthread_createtakes the location at the beginning of the array (&tid[0]), which is a pointer, and allocates a block of memory to hold the pthread data structure. The pointer is set to point to the new data structure and the data structure is allocated.

Thepthread_create获取数组开头的位置(&tid[0]),它是一个指针,并分配一块内存来保存 pthread 数据结构。指针被设置为指向新的数据结构并分配数据结构。

Your last question --- the difference between malloc(n*sizeof(int))and calloc(n,sizeof(int))is that the later initializes each byte to 0, while the first does not.

您的最后一个问题 --- 和 之间的区别在于malloc(n*sizeof(int))calloc(n,sizeof(int))后者将每个字节初始化为0,而第一个则没有。