I am trying to malloc and free a small array/table of single letter strings. I know that this can be done in an array, but I want to try and do this with a malloc and free.
I have this right now:
char **letters = (char**) malloc(5 * sizeof(char*));
int i =0;
for(i=0; i < NUMLETTERS ; ++i )
{
letters[i] = (char*) malloc(2*sizeof(char)); //2 is for the letter and null terminator
}
letters[0] = "a";
letters[1] = "b";
letters[2] = "c";
letters[3] = "d";
letters[4] = "e";
//Do stuff here
int i =0;
for(i=0; i < 5; ++i )
{
free(letters[i]);
}
free(letters);
The above code compiles fine and my code in between also works and runs fine, but at runtime it gets an error during the free parts. Also, after using valgrind..it says that the free(letters[i]); is invalid.
Any help?
The problem is here:
You are overwriting each of your malloc’ed pointers with string literals. Then you free them in the final loop. Since you are effectively freeing the string literals, it fails.
There are two ways to solve this:
1: You don’t need the inner allocation if you are just assigning string literals to them. So get rid of both loops.
2:
strcpyeach of the string literals instead.