[Baypiggies] ctypes presentation material online

Marilyn Davis marilyn at deliberate.com
Fri May 12 21:21:00 CEST 2006

On Fri, 12 May 2006, Stephen McInerney wrote:

> The case below is a good argument for static type checking?
> Is there any type checker smart enough to understand that
> string + 1 is unlikely to have semantic meaning.

Good thought.

But although it is unlikely, it is entirely possible.  string + 1 in C
is string[1:] in Python.  It trims off the first character.

string is defined as a char *, which is the address of the first
character.  All string processing is convention, not a built-in data
type.  The string is assumed to reside at the memory address in
contiguous bytes until there is a '\0', marking the end.  That is why
it takes strlen(string + 1) to malloc memory for it: the length of the
string plus one byte for that '\0' flag to mark the end.

And that is why, string + 1, which is the address of the second
character, is string[1:].

When I teach C, I encourage students memorize only 3 things:

1.  The point of a programming language is to communicate with other
engineers that the computer also understands.

2.  The name of an array is shorthand for the address of the first
element of the array.

3.  A string is an array of characters with a '\0' at the end.

2 and 3 are very hard.

Teaching Python, they only get #1.

I love it.


> (I know this is C but the concept is generic.)
> >From: Marilyn Davis <marilyn at deliberate.com>
> >
> >Yeh.  Memory bugs are just terrible to find.
> >
> >I once had one in C code where I was mallocing space for a new string:
> >
> >buf = malloc(len(string + 1));
> >
> >My eyeball looked at that a jillion times before I realized that I had
> >a misplaced ')' and it should be:
> >
> >buf = malloc(len(string) + 1);
> >
> >The problem is that it crashed much later, after I wrote to the space
> >(and overwrote the memory), and then it finally crashed in another
> >call to malloc.


More information about the Baypiggies mailing list