C fixes

Follow-up to #3653: some more C fixes and cleanup. Highlight is the fixing of a few unchecked mallocs; there are more of these in the codebase. Also, I removed some casts of the form

    char *p = (char *)malloc(n);

which are useless, since C will convert a `void*` to any other pointer automatically; this casting style is more likely to [hide bugs](http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc) than to fix them.