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

C[omp]ute

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.

Last 100 entries

Interesting (But Largely Illegible) Typeface; Retiring Essentialism; Poorest in UK, Poorest in N Europe; I Want To Be A Redneck!; Reverse Racism; The Lost Art Of Nomography; IBM Data Center (Photo); Interesting Account Of Gamma Hack; The Most Interesting Audiophile In The World; How did the first world war actually end?; Ky - Restaurant Santiago; The Black Dork Lives!; The UN Requires Unaninmous Decisions; LPIR - Steganography in Practice; How I Am 6; Clear Explanation of Verizon / Level 3 / Netflix; Teenage Girls; Formalising NSA Attacks; Switching Brakes (Tektro Hydraulic); Naim NAP 100 (Power Amp); AKG 550 First Impressions; Facebook manipulates emotions (no really); Map Reduce "No Longer Used" At Google; Removing RAID metadata; New Bike (Good Bike Shop, Santiago Chile); Removing APE Tags in Linux; Compiling Python 3.0 With GCC 4.8; Maven is Amazing; Generating Docs from a GitHub Wiki; Modular Shelves; Bash Best Practices; Good Emergency Gasfiter (Santiago, Chile); Readings in Recent Architecture; Roger Casement; Integrated Information Theory (Or Not); Possibly undefined macro AC_ENABLE_SHARED; Update on Charges; Sunburst Visualisation; Spectral Embeddings (Distances -> Coordinates); Introduction to Causality; Filtering To Help Colour-Blindness; ASUS 1015E-DS02 Too; Ready Player One; Writing Clear, Fast Julia Code; List of LatAm Novels; Running (for women); Building a Jenkins Plugin and a Jar (for Command Line use); Headphone Test Recordings; Causal Consistency; The Quest for Randomness; Chat Wars; Real-life Financial Co Without ACID Database...; Flexible Muscle-Based Locomotion for Bipedal Creatures; SQL Performance Explained; The Little Manual of API Design; Multiple Word Sizes; CRC - Next Steps; FizzBuzz; Update on CRCs; Decent Links / Discussion Community; Automated Reasoning About LLVM Optimizations and Undefined Behavior; A Painless Guide To CRC Error Detection Algorithms; Tests in Julia; Dave Eggers: what's so funny about peace, love and Starship?; Cello - High Level C Programming; autoreconf needs tar; Will Self Goes To Heathrow; Top 5 BioInformatics Papers; Vasovagal Response; Good Food in Vina; Chilean Drug Criminals Use Subsitution Cipher; Adrenaline; Stiglitz on the Impact of Technology; Why Not; How I Am 5; Lenovo X240 OpenSuse 13.1; NSA and GCHQ - Psychological Trolls; Finite Fields in Julia (Defining Your Own Number Type); Julian Assange; Starting Qemu on OpenSuse; Noisy GAs/TMs; Venezuela; Reinstalling GRUB with EFI; Instructions For Disabling KDE Indexing; Evolving Speakers; Changing Salt Size in Simple Crypt 3.0.0; Logarithmic Map (Moved); More Info; Words Found in Voynich Manuscript; An Inventory Of 3D Space-Filling Curves; Foxes Using Magnetic Fields To Hunt; 5 Rounds RC5 No Rotation; JP Morgan and Madoff; Ori - Secure, Distributed File System; Physical Unclonable Functions (PUFs); Prejudice on Reddit; Recursion OK; Optimizing Julia Code; Cash Handouts in Brazil; Couple Nice Music Videos; It Also Works!

© 2006-2013 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:

    list.h:

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

    list.c:

        #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:

    list.h:

        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
itself.

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.

Andrew

https://sites.google.com/site/cinterfacesimplementations/
http://www.amazon.com/dp/0201498413

Comment on this post