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

Jump to

Quick reference

Showing posts with label malloc. Show all posts
Showing posts with label malloc. Show all posts

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);
}
These warnings:

warning: initialization makes pointer from integer without a cast
warning: assignment makes pointer from integer without a cast

...for a line containing malloc could mean that you forgot to #include "stdlib.h".
Functions are assumed to return an integer type by default if not declared.