A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.
Jump to
Showing posts with label memory. Show all posts
Showing posts with label memory. 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);
}
Labels:
c,
code,
malloc,
memory,
programming
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.
Subscribe to:
Posts (Atom)