Search code examples
ckernighan-and-ritchie

K&R Chapter 5.4: Questions on passage regarding stacks


I am on Chapter 5.4 of the "C Programming Language (2nd Edition)" and I came across a passage regarding memory allocation that I cannot get a mental grasp of:

In reference to the book's rudimentary implementation of memory allocation with the functions alloc(n) and 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;

The problem I have understanding is when the passage states the routines are 'rudimentary' because calls to afree must be made in the opposite order to the calls made on alloc. Does that mean the function afree must be called first before making use of the function alloc? I understand how the stack data structure behaves but I am unsure of its context in stating the function calls "must be made in the opposite order".

Also, the the last sentence of the paragraph states malloc and free having no such restrictions. What are the restrictions they are referring to?


Solution

  • I think an example will best explain this.

    If I make the calls:

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

    I must call afree in this order:

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

    That is the rudimentary implementation. In the C language you do not need to call free in reverse order of how you called malloc. You can malloc multiple times and then free later.