什么是malloc()函数在C一些有用的例子吗? [英] What are some useful examples of malloc() in C?

查看:316
本文介绍了什么是malloc()函数在C一些有用的例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是阅读的malloc()用C

借助维基百科的文章提供的例如,但它甫一为10整数比较数组与 int数组[10]分配足够的内存。不是很有用。

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

当你决定使用的malloc()对C处理内存的吗?

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

推荐答案

动态数据结构(列表,树等)使用的malloc 来分配在堆上他们的节点。例如:

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

/* 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;
}

考虑数据的方式是新添加到列表中以 sl_insert_front 。您需要创建将保存数据和指针列表中的下一个节点一个节点。你要去哪里建立呢?

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?


  • 也许堆栈! - - 在将在该栈空间分配?在哪些功能?会有什么变化时,函数退出?

  • 也许在静态内存! - - 那么你就必须事先知道你有多少列表中的节点,因为有静态内存为pre-分配的程序加载时

  • 在堆? - 因为有你有所有必需的灵活性

  • 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.

的malloc 在C用于在堆中分配的东西 - 内存空间可以增长,并在运行时动态收缩,且其所有权完全编程的控制之下。还有更多的例子,这是非常有用的,但我在这里展示的一个是重新presentative之一。最终,在复杂的C程序,你会发现,大多数程序的数据是在堆上,通过指针访问。正确的程序始终知道哪个指针拥有数据,并仔细清理,当它不再需要分配的内存。

malloc is 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一些有用的例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆