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 to do it with malloc and for free.

I have it 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 between them also works and works fine, but at runtime it gets an error during the free parts. Also, after using valgrind..it says it is free (letters [i]); not valid.

Any help?

+6
source share
2 answers

The problem is here:

 letters[0] = "a"; letters[1] = "b"; letters[2] = "c"; letters[3] = "d"; letters[4] = "e"; 

You rewrite each malloc'ed pointer with string literals. Then you release them in the last cycle. Since you are effectively freeing string literals, this fails.

There are two ways to solve this problem:

1: you don't need inner highlighting if you just assign them string literals. Therefore, get rid of both loops.

2: strcpy each of the string literals.

+5
source

You allocate memory correctly for each row in the array, but then you are not using that memory. Instead, you change the char* pointers in each of the five elements of the array to point to the string literals "a", "b", "c", etc.

So, you have lost references to the original memory that you allocated, and instead you are trying to free memory that does not belong to you.

Instead of assigning pointers to strings as follows:

 letters[0] = "a"; 

you must copy the string to the allocated memory, for example:

 strncpy(letters[0], "a", 2); 
+3
source

Source: https://habr.com/ru/post/899553/


All Articles