- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在《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/
这是一个关于编程风格的一般性问题。假设我有一个对象 Line,它有一些方法和私有(private)变量 Point point_a_ 和 Point point_b_。比方说,在某些时候我需要改变这两
ISNULL and COALESCE though equivalent, can behave differently. An expression involving ISNULL with n
我正在开发一个基于 Web 的租赁管理应用程序,该应用程序需要能够根据数据库中任何给定时间的信息每天生成各种报告、提醒和警报。此类报告、提醒和警报的一些示例包括: 发送一封交易电子邮件,让一组用户知道
我在《C程序设计语言(第2版)》第5.4章,遇到一段关于内存分配的内容,脑子里想不通: 引用书中使用函数 alloc(n) 和 afree(p) 进行内存分配的基本实现 C is consistent
我是一名优秀的程序员,十分优秀!