A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Freeing memory in C

If you allocate memory in a subroutine for a variable that you then return, you’ve got to free the variable you return:
 
char * allocstring(char * text)
{
    char * s = malloc(s, strlen(text)+1);
    strcpy(s, text);
    return s;
}
 
void main()
{
    char * s = allocstring(“Hello World”);
    free(s);
}