| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next


Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

C-ORM: docs, API.

Last 100 entries

Small Success With Go!; Re: Quick message - This link is broken; Adding Reverb To The Echo Chamber; Sox Audio Tools; Would This Have Been OK?; Honesty only important economically before institutions develop; Stegangraphy via PS4; OpenCL Mess; More Book Recommendations; Good Explanation of Difference Between Majority + Minority; Musical Chairs - Who's The Privileged White Guy; I can see straight men watching this conversation and laffing; When it's Actually a Source of Indignation and Disgust; Meta Thread Defending POC Causes POC To Close Account; Indigenous People Of Chile; Curry Recipe; Interesting Link On Marginality; A Nuclear Launch Ordered, 1962; More Book Recs (Better Person); It's Nuanced, And I Tried, So Back Off; Marx; The Negative Of Positive; Jenny Holzer Rocks; Huge Article on Cultural Evolution and More; "Ignoring language theory"; Negative Finger Counting; Week 12; Communication Via Telecomm Bids; Finding Suspects Via Relatives' DNA From Non-Crime Databases; Statistics and Information Theory; Ice OK in USA; On The Other Hand; (Current Understanding Of) Chilean Taxes / Contributions; M John Harrison; Playing Games on a Cloud GPU; China Gamifies Real Life; Can't Help Thinking It's Thoughtcrime; Mefi Quotes; Spray Painting Bike Frame; Weeks 10 + 11; Change: No Longer Possible To Merge Metadata; Books on Old Age; Health Tree Maps; MRA - Men's Rights Activists; Writing Good C++14; Risk Assessment - Fukushima; The Future of Advertising and Surveillance; Travelling With Betaferon; I think I know what I dislike so much about Metafilter; Weeks 8 + 9; More; Pastamore - Bad Italian in Vitacura; History Books; Iraq + The (UK) Governing Elite; Answering Some Hard Questions; Pinochet: The Dictator's Shadow; An Outsider's Guide To Julia Packages; Nobody gives a shit; Lepton Decay Irregularity; An Easier Way; Julia's BinDeps (aka How To Install Cairo); Good Example Of Good Police Work (And Anonymity Being Hard); Best Santiago Burgers; Also; Michael Emmerich (Vibrator Translator) Interview (Japanese Books); Clarice Lispector (Brazillian Writer); Books On Evolution; Looks like Ara (Modular Phone) is dead; Index - Translations From Chile; More Emotion in Chilean Wines; Week 7; Aeon Magazine (Science-ish); QM, Deutsch, Constructor Theory; Interesting Talk Transcripts; Interesting Suggestion Of Election Fraud; "Hard" Books; Articles or Papers on depolarizing the US; Textbook for "QM as complex probabilities"; SFO Get Libor Trader (14 years); Why Are There Still So Many Jobs?; Navier Stokes Incomplete; More on Benford; FBI Claimed Vandalism; Architectural Tessellation; Also: Go, Blake's 7; Delusions of Gender (book); Crypto AG DID work with NSA / GCHQ; UNUMS (Universal Number Format); MOOCs (Massive Open Online Courses); Interesting Looking Game; Euler's Theorem for Polynomials; Weeks 3-6; Reddit Comment; Differential Cryptanalysis For Dummies; Japanese Graphic Design; Books To Be Re-Read; And Today I Learned Bugs Need Clear Examples; Factoring a 67 bit prime in your head; Islamic Geometric Art; Useful Julia Backtraces from Tasks; Nothing, however, is lost with less discomfort than that which, when lost, cannot be missed

© 2006-2015 Andrew Cooke (site) / post authors (content).

C Interfaces and Implementations (A Review)

From: andrew cooke <andrew@...>

Date: Sat, 19 May 2012 03:15:10 -0400

I've seen this book recommended for people who know C and want to improve.
And it is, I think, something of a classic, originally published in 1996.

Recently I've been working in C.  While I enjoy some aspects of the language I
wasn't too happy with my project (now drawing to a close).  Looking round for
a possible cure for the ills I felt in my code, I decided to read this book.

In retrospect, I think the problems with my code come from the usual
compromises that responsible, professional development involves (there is
certainly room for improvement, but the skills needed are likely "softer" than
those discussed here).

Before coming to that conclusion I bought and read this book.  That it didn't
help me is my own fault (see above), but I am not convinced how much it will
help others, either.

It does teach an important technique: the use of abstract data types (ADTs) in
C.  This is possible because you can name a struct separately from its
definition (as you can a function - this is what header files are for).  With
care this can be used to define an interface that depends on a type whose
details are opaque to the user.

For example, consider a (partial) API for linked lists:


        typedef struct list_struct *LIST;
        LIST append(LIST list, void *data);
        int length(LIST list);


        #include "list.h"

        struct {
            void *head;
            LIST tail;
        } list_struct;

        LIST append(LIST list, void *data) {
            LIST next = calloc(1, sizeof(*next));
            next->tail = list;
            next->head = data;
            return next;


You can see that someone using the API, who would include only list.h in their
code, would know nothing of the internal structure of lists.  This means that
the implementation can be changed without harming the client code (assuming
that the contracts between client and library are clear).

(Forgive me if I have an error above - I haven't compiled it - but I hope it's
clear enough to give the general idea).

If you look at the code above, you might wonder what could change.  What makes
a good API?  One interesting technical question is: why is LIST defined as a
pointer?  Why the above, rather than:


        typedef struct list_struct LIST;
        LIST *append(LIST *list, void *data);
        int length(LIST *list);

Maybe that seems like a trivial detail, but it raises an interesting issue:
the initial approach makes the use of "const" invalid.

In other words:

        typedef struct list_struct *LIST;
        LIST append(const LIST list, void *data);

is silly (it's just guaranteeing the constness of the pointer, not the struct
itself).  In contrast

        typedef struct list_struct LIST;
        LIST append(const LIST *list, void *data);

is saying something about the list itself.  So isn't that better?  I must
admit that I generally prefer the latter approach for a much more practical
reason - I get less confused about levels of indirection.  But Hanson (the
author of CI&I) argues that it places constraints on the implementation.  For
example, a hashtable might reasonably want to resize during an insert, or some
optimisation might imply lazy initialisation.

It's a valid point, and something I am glad I read.  Unfortunately that was
the best part, just 29 pages in.

Now at this point I should say that I may be to blame.  I may just be too lazy
- the book might repay a more detailed reading than I managed.  Because, while
I read with the best of intentions, I found that there were times when I had
no real recollection of the previous few pages.

The problem, I feel, is that this book is written as "literate code".  That
means that every line of the library appears in the book.  Which has to mean
that many sections are, frankly, mundane detail.

Worse, the literate approach gives the entire book a very flat structure.
Each chapter is arranged with a description of the interface before the
implementation.  Which might lead you to hope that the first section of each
chapter will give a high-level overview of the design.  But it doesn't really
work like that - the initial sections tend to be vague and incomplete.
Largely, I suspect, so that the later sections aren't quite so boring.

And the library developed - while useful - doesn't dogfood itself.  In other
words, most parts of the library are implemented in isolation.  There are a
few exceptions where there's an obvious layered approach (for example, text
processing built on low level strings, or an arbitrary precision calculator
built on a library for extended precision positive integers), but that's
pretty much all: the hash table (chapter 8), for example, isn't used by the
"atoms" library (chapter 3), which instead implements a hash table all by

Perhaps there a reason for this duplication, but that kind of explanation was
what I missed most - there's very little (apart from the reasoning on ADTs
above) to justify the choices made.

An example of this lack of explanation is the choice of indexing.  Various
APIs allow indexing from either end of a sequence (eg to access characters
counting left from the end of a string).  The common convention is to use
indexes to the right starting from 1, and indexes to the left starting from 0,
counting down (if you just skimmed that sentence, go back and think about it.
Yeah.  Weird).

As far as I can tell, the motivation for this is (1) that is how Icon does
(did?) it and (2) this schema means indices in the two directions are unique,
letting you specify a pair of indices (for a range) in either order.

Obviously it's hard to judge historical decisions when clouded by current
conventions (Python stays consistent with C's zero indexing, supports
backwards indexing from -1, and expects pairs to be ordered left-right), but
as far as I remember, even back in 96, Icon was not *that* big a deal.  And
breaking C's conventions in a C library seems, well, at the very least
something you should justify in detail.

While I remember - one other symptom of age is that the Threads library, which
uses assembler, doesn't support x86.

Another example of where I would have appreciated more analysis was in the
choice of representation for signed, arbitrary precision integers.  The
implementation here uses a separate flag for sign.  I am unsure why that was
chosen rather than a two's complement approach, or why the flag doesn't also
indicate zero (I'm not saying that these would be better; I just expected this
book to be the kind of book that explains such things).

So there could be more "high-level" explanations.  There could also be less
"low-level" detail.  There is a chapter for lists and another for
double-linked lists (called rings).  Both might be useful in a library, but in
a book they are 90% duplication.  And the difference between vectors (called
sequences) and dynamic arrays is even smaller (in passing, note that although
one advantage of ADTs is that you can swap implementations, these pairs cannot
be swapped, even though I suspect that in both cases one is a subset of the
other; again, I am not saying that would be good, just that it would be nice
to have heard why that choice was made).

Oh, and there are exercises.  Some of which address the design issues.  None
of which have answers.  So I guess if Hanson was your lecturer you got a
better deal.

In conclusion, this book has a good idea: ADTs.  It hammers that idea home in
the detail you would expect when every line of code is described.  But it
otherwise lacks the discussion of general principles you would expect for an
"advanced" text, it's dated in parts, and I am not sure that all of the
contents made sense even back when it was written.



Comment on this post