我正在阅读有关 C 中的 malloc()
的内容。
Wikipedia article提供一个 example ,但是与 int array[10]
相比,它只是为 10 个整数的数组分配了足够的内存。不是很有用。
您什么时候决定使用 malloc()
而不是 C 为您处理内存?
最佳答案
动态数据结构(列表、树等)使用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;
}
考虑如何使用 sl_insert_front
将新数据添加到列表中。您需要创建一个节点来保存数据和指向列表中下一个节点的指针。你打算在哪里创建它?
- 也许在堆栈上! - NO - 该堆栈空间将分配到哪里?在哪个函数中?当函数退出时它会发生什么?
- 也许在静态内存中! - NO - 然后您必须提前知道您有多少个列表节点,因为静态内存是在程序加载时预先分配的。
- 在堆上? 是 - 因为您拥有所有必需的灵 active 。
malloc
在 C 语言中用于分配堆上的东西——可以在运行时动态增长和收缩的内存空间,其所有权完全在程序员的控制之下。还有很多这样的例子很有用,但我在这里展示的是一个有代表性的例子。最终,在复杂的 C 程序中,您会发现程序的大部分数据都在堆上,可以通过指针访问。正确的程序总是知道哪个指针“拥有”数据,并会在不再需要时仔细清理分配的内存。
关于c - C 中 malloc() 的一些有用示例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4084950/