Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to malloc char** table?

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?

like image 542
Flipper Avatar asked Oct 18 '11 19:10

Flipper


People also ask

Do you need to malloc for char *?

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.

How do you allocate memory to the array of char pointers?

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) );

How many bytes will malloc sizeof char * 10 allocate on a 64 bit machine?

malloc(10) allocates 10 bytes, which is enough space for 10 chars.

How do you dynamically allocate a char array?

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.


1 Answers

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.

like image 162
Mysticial Avatar answered Oct 06 '22 06:10

Mysticial