什么是C中的malloc()? (What is malloc() in C?)
malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored.
malloc()是一个库函数,它允许C从堆动态分配内存。 堆是存储内容的内存区域。
malloc() is part of stdlib.h and to be able to use it you need to use #include <stdlib.h>
.
malloc()是stdlib.h的一部分,要使用它,您需要使用#include <stdlib.h>
。
如何使用Malloc (How to Use Malloc)
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block. To hold this returned pointer, we must create a variable. The pointer should be of same type used in the malloc statement.Here we’ll make a pointer to a soon-to-be array of ints
malloc()分配请求大小的内存,并返回指向已分配块开头的指针。 要保留此返回的指针,我们必须创建一个变量。 该指针应与malloc语句中使用的类型相同。在这里,我们将创建一个指向即将成为整数的数组的指针。
int* arrayPtr;
Unlike other languages, C does not know the data type it is allocating memory for; it needs to be told. Luckily, C has a function called sizeof()
that we can use.
与其他语言不同,C不知道它为其分配内存的数据类型。 它需要被告知。 幸运的是,C有一个我们可以使用的名为sizeof()
的函数。
arrayPtr = (int *)malloc(10 * sizeof(int));
This statement used malloc to set aside memory for an array of 10 integers. As sizes can change between computers, it’s important to use the sizeof() function to calculate the size on the current computer.
该语句使用malloc为10个整数的数组留出内存。 由于大小可以在计算机之间改变,因此使用sizeof()函数计算当前计算机上的大小非常重要。
Any memory allocated during the program’s execution will need to be freed before the program closes. To free
memory, we can use the free() function
在程序关闭之前,必须先释放程序执行期间分配的所有内存。 要free
内存,我们可以使用free()函数
free( arrayPtr );
This statement will deallocate the memory previously allocated. C does not come with a garbage collector
like some other languages, such as Java. As a result, memory not properly freed will continue to be allocated after the program is closed.
该语句将取消分配先前分配的内存。 C没有像Java之类的其他语言那样带有garbage collector
。 因此,关闭程序后,将继续分配未正确释放的内存。
在继续之前... (Before you go on…)
回顾 (A Review)
- Malloc is used for dynamic memory allocation and is useful when you don’t know the amount of memory needed during compile time. Malloc用于动态内存分配,当您在编译时不知道所需的内存量时很有用。
- Allocating memory allows objects to exist beyond the scope of the current block. 分配内存允许对象存在于当前块的范围之外。
- C passes by value instead of reference. Using malloc to assign memory, and then pass the pointer to another function, is more efficient than having the function recreate the structure. C通过值而不是引用传递。 使用malloc分配内存,然后将指针传递给另一个函数,比让函数重新创建结构更有效。
有关C编程的更多信息: (More info on C Programming:)
翻译自: https://www.freecodecamp.org/news/malloc-in-c-dynamic-memory-allocation-in-c-explained/