Half-baked ideas: C: please let me free (static data)

For more half-baked ideas, see the ideas tag.

In modern C, you can free (NULL) safely. I’d like to suggest a small extension: let it be safe to free static data too.

This would avoid many cases where we end up with a “useless” strdup, as in the pseudo-code below:

freeable char *
type_to_string (union type u)
  switch (u.type) {
  case INT: return "int"; // strdup avoided
  case CHAR: return "char"; // strdup avoided
  case STRUCT:
    asprintf (&str, "struct %s",
              type_to_string (u.strct.t));
    return str;

Notice that

free (type_to_string (u));

would work, whether the type u was INT, CHAR or STRUCT.

This feature is inspired by OCaml. In OCaml, the garbage collector keeps track of pages allocated on the OCaml heap versus everything else, in a hash table. It uses the hash table to avoid following pointers outside the OCaml heap. This gives you great flexibility: an OCaml “pointer” can point to arbitrary stuff if you want (eg. C-allocated structures, static data), and the GC just ignores it. This makes clever stuff like OCaml ancient possible.

A C implementation of this would also need to track which pages come from the C heap, and which pages are static data. It’s quite possible that most C malloc implementations can or do have this already. glibc certainly seems to be able to detect when you free up a non-heap pointer.

Eagle-eyed reviewers will have noted this would break “const correctness” (which is a very woolly and broken concept in C anyway, compared to functional languages). It needs a new class of pointers which can be freed but cannot be written to. I used freeable char * in the pseudo-code above.



Filed under Uncategorized

3 responses to “Half-baked ideas: C: please let me free (static data)

  1. Joe User

    It might be interesting if C added isstatic() and isheap() functions.
    Then you could do:
    myfree(char *p) {
    if (isheap(p)) free(p);
    But also other useful stuff.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.