gpt4 book ai didi

c - K&R 第 5.4 章 : Questions on passage regarding stacks

转载 作者:太空宇宙 更新时间:2023-11-04 00:48:43 25 4
gpt4 key购买 nike

我在《C程序设计语言(第2版)》第5.4章,遇到一段关于内存分配的内容,脑子里想不通:

引用书中使用函数 alloc(n) 和 afree(p) 进行内存分配的基本实现

C is consistent and regular in its approach to address arithmetic; its integration of pointers, arrays, and address arithmetic is one of the strengths of the language. Let us illustrate by writing a rudimentary storage allocator. There are two routines. The first, alloc(n), returns a pointer to n consecutive character positions, which can be used by the caller of alloc for storing characters. The second, afree(p), releases the storage thus acquired so it can be re-used later. The routines are ``rudimentary'' because the calls to afree must be made in the opposite order to the calls made on alloc. That is, the storage managed by alloc and afree is a stack, or last-in, first-out. The standard library provides analogous functions called malloc and free that have no such restrictions;

我理解的问题是当段落指出例程是“基本的”时,因为对 afree 的调用必须以与对 alloc 的调用相反的顺序进行。这是否意味着在使用函数 alloc 之前必须先调用函数 afree?我了解堆栈数据结构的行为方式,但我不确定它在声明函数调用“必须以相反顺序进行”时的上下文。

此外,该段的最后一句声明 malloc 和 free 没有此类限制。他们指的是什么限制?

最佳答案

我认为一个例子可以最好地解释这一点。

如果我打电话:

a = alloc(10);
b = alloc(10);
c = alloc(10);

我必须按以下顺序调用 afree:

afree(c);
afree(b);
afree(a);

这是基本的实现。在 C 语言中,您不需要按照调用 malloc 的相反顺序调用 free。您可以 malloc 多次,然后再释放。

关于c - K&R 第 5.4 章 : Questions on passage regarding stacks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com