C语言 C 中有哪些有用的 malloc() 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4084950/
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 06:53:53  来源:igfitidea点击:

What are some useful examples of malloc() in C?

cmalloc

提问by alex

I'm just reading about malloc()in C.

我只是在读malloc()C 语言。

The Wikipedia articleprovides an example, however it justs allocate enough memory for an array of 10 ints in comparison with int array[10]. Not very useful.

维基百科文章提供了一个例子,但它甫一为10个整数与比较阵列分配足够的内存int array[10]。不是很有用。

When would you decided to use malloc()over C handling the memory for you?

你什么时候决定使用malloc()over C 为你处理内存?

回答by Eli Bendersky

Dynamic data structures (lists, trees, etc.) use mallocto allocate their nodes on the heap. For example:

动态数据结构(列表、树等)用于malloc在堆上分配它们的节点。例如:

/* A singly-linked list node, holding data and pointer to next node */
struct slnode_t
{
    struct slnode_t* next;
    int data;
};

typedef struct slnode_t slnode;

/* Allocate a new node with the given data and next pointer */
slnode* sl_new_node(int data, slnode* next)
{
    slnode* node = malloc(sizeof *node);
    node->data = data;
    node->next = next;
    return node;
}

/* Insert the given data at the front of the list specified by a 
** pointer to the head node
*/
void sl_insert_front(slnode** head, int data)
{
    slnode* node = sl_new_node(data, *head);
    *head = node;
}

Consider how new data is added to the list with sl_insert_front. You need to create a node that will hold the data and the pointer to the next node in the list. Where are you going to create it?

考虑如何使用 将新数据添加到列表中sl_insert_front。您需要创建一个节点来保存数据和指向列表中下一个节点的指针。你打算在哪里创建它?

  • Maybe on the stack! - NO- where will that stack space be allocated? In which function? What happens to it when the function exits?
  • Maybe in static memory! - NO- you'll then have to know in advance how many list nodes you have because static memory is pre-allocated when the program loads.
  • On the heap? YES- because there you have all the required flexibility.
  • 也许在堆栈上!-- 将在哪里分配堆栈空间?在哪个功能?当函数退出时会发生什么?
  • 也许在静态内存中!-- 然后您必须提前知道您有多少个列表节点,因为在程序加载时预先分配了静态内存。
  • 在堆上?是的- 因为在那里您拥有所有必需的灵活性。

mallocis used in C to allocate stuff on the heap - memory space that can grow and shrink dynamically at runtime, and the ownership of which is completely under the programmer's control. There are many more examples where this is useful, but the one I'm showing here is a representative one. Eventually, in complex C programs you'll find that most of the program's data is on the heap, accessible through pointers. A correct program always knows which pointer "owns" the data and will carefully clean-up the allocated memory when it's no longer needed.

malloc在 C 中用于在堆上分配东西 - 可以在运行时动态增长和收缩的内存空间,其所有权完全在程序员的控制之下。还有更多有用的示例,但我在这里展示的示例是一个具有代表性的示例。最终,在复杂的 C 程序中,您会发现程序的大部分数据都在堆上,可以通过指针访问。一个正确的程序总是知道哪个指针“拥有”数据,并在不再需要时小心地清理分配的内存。

回答by Antoine Pelisse

What if you don't know the size of the array when you write your program ? As an example, we could imagine you want to load an image. At first you don't know its size, so you will have to read the size from the file, allocate a buffer with this size and then read the file in that buffer. Obviously you could not have use a static size array.

如果在编写程序时不知道数组的大小怎么办?举个例子,我们可以想象你想要加载一个图像。一开始你不知道它的大小,所以你必须从文件中读取大小,分配一个具有这个大小的缓冲区,然后在该缓冲区中读取文件。显然,您不能使用静态大小数组。

EDIT:

编辑:

Another point is: When you use dynamic allocation, memory is allocated on the heap while arrays are allocated on the stack. This is quite important when you are programming on embedded device as stack can have a limited size compared to heap.

还有一点是:当你使用动态分配时,内存是在堆上分配的,而数组是在栈上分配的。当您在嵌入式设备上编程时,这非常重要,因为与堆相比,堆栈的大小可能有限。

回答by rerun

In the example you described int array[10]goes away when you leave your stack frame. If you would like the used memory to persist beyond local scope you have to use malloc();

在您描述的示例中int array[10],当您离开堆栈框架时就会消失。如果您希望使用的内存超出本地范围,则必须使用 malloc();

回答by tidwall

I recommend that you google Stack and Heap.

我建议你谷歌Stack 和 Heap

int* heapArray = (int*)malloc(10 * sizeof(int));
int stackArray[10];

Both are very similar in the way you access the data. They are very different in the way that the data is stored behind the scenes. The heapArray is allocated on the heap and is only deallocted when the application dies, or when free(heapArray)is called. The stackArray is allocated on the stack and is deallocated when the stack unwinds.

两者在访问数据的方式上都非常相似。它们在后台存储数据的方式上有很大不同。heapArray 在堆上分配,并且仅在应用程序终止或被free(heapArray)调用时才解除分配。stackArray 在堆栈上分配,并在堆栈展开时释放。

回答by Kel

malloc() is used whenever:

malloc() 在以下情况下使用:

  1. You need dynamic memory allocation
    If you need to create array of size n, where n is calculated during your program execution, the only way you can do it is using malloc().

  2. You need to allocate memory in heap
    Variables defined in some functions live only till the end of this function. So, if some "callstack-independent" data is needed, it must be either passed/returned as function parameter (which is not always suitable), or stored in heap. The only way to store data in heap is to use malloc(). There are variable-size arrays, but they are allocated on stack.

  1. 您需要动态内存分配
    如果您需要创建大小为 n 的数组,其中 n 是在程序执行期间计算的,那么唯一的方法就是使用 malloc()。

  2. 您需要在堆中分配内存
    某些函数中定义的变量只存在到该函数结束。因此,如果需要一些“与调用堆栈无关”的数据,则必须将其作为函数参数传递/返回(这并不总是合适的),或者存储在堆中。在堆中存储数据的唯一方法是使用 malloc()。有可变大小的数组,但它们是在堆栈上分配的。

回答by paxdiablo

Although you can do variable length arrays as of C99, there's still no decent substitute for the more dynamic data structures. A classic example is the linked list. To get an arbitrary size, you use mallocto allocate eachnode so that you can insert and delete without massive memory copying, as would be the case with a variable length array.

尽管从 C99 开始您可以使用可变长度数组,但仍然没有更好的替代品来替代更动态的数据结构。一个经典的例子是链表。为了获得任意大小,您使用malloc分配每个节点,以便您可以在不进行大量内存复制的情况下插入和删除,就像可变长度数组的情况一样。

For example, an arbitrarily sized stack using a simple linked list:

例如,使用简单链表的任意大小的堆栈:

#include <stdio.h>
#include <stdlib.h>

typedef struct sNode {
    int payLoad;
    struct sNode *next;
} tNode;

void stkPush (tNode **stk, int val) {
    tNode *newNode = malloc (sizeof (tNode));
    if (newNode == NULL) return;
    newNode->payLoad = val;
    newNode->next = *stk;
    *stk = newNode;
}

int stkPop (tNode **stk) {
    tNode *oldNode;
    int val;
    if (*stk == NULL) return 0;
    oldNode = *stk;
    *stk = oldNode->next;
    val = oldNode->payLoad;
    free (oldNode);
    return val;
}

int main (void) {
    tNode *top = NULL;
    stkPush (&top, 42);
    printf ("%d\n", stkPop (&top));
    return 0;
}

Now, it's possibleto do this with variable length arrays but, like writing an operating system in COBOL, there are better ways to do it.

现在,可以使用可变长度数组来做到这一点,但是,就像在 COBOL 中编写操作系统一样,有更好的方法来做到这一点。