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?
As was indicated by others, you don't need to use malloc just to do: const char *foo = "bar"; The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable.
In C, the RAM should use the following code to allocate the two-dimensional array: *contents = (char**) malloc(sizeof(char*) * numRows); **contents = (char*) malloc(sizeof(char) * numColumns * numRows); for(i = 0; i < numRows; i++) (*contents)[i] = ( (**contents) + (i * numColumns) );
malloc(10) allocates 10 bytes, which is enough space for 10 chars.
Use the new() Operator to Dynamically Allocate Array in C++ Then, we dynamically allocate the char array and assign the corresponding values to its elements in the for loop body. Note that the delete operator must be explicitly called once the memory associated with the arr pointer is no longer needed.
The problem is here:
letters[0] = "a";
letters[1] = "b";
letters[2] = "c";
letters[3] = "d";
letters[4] = "e";
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: strcpy
each of the string literals instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With