Search code examples
cstringpointerscharrealloc

Allocate memory on pointed pointer to char


I am trying to realloc my word list with the word number counter (assume it is set previously). I stick on a segmentation fault at the reallocation line. The word pointer is char-sized. Where is the actual problem ?

// counter
int word_nb = 3;
// buffer allocation
char **word_list;
word_list = (char **)malloc(sizeof(char*));
if (word_list == NULL) {
    /*error handling*/
    printf("error word list allocation\\n");
}
*word_list = (char *)malloc(sizeof(char));
if (*word_list == NULL) {
    /*error handling*/
    printf("error current word into list allocation\\n");
}
char *word = (char *)malloc(sizeof(char));
if (word == NULL) {
    /*error handling*/
    printf("error word allocation\\n");
}
// realloc to correct size
for(int a = 0; a < word_nb; a++) 
{
    *(word_list + (word_nb-1)) = (char *)realloc(*(word_list + (word_nb-1)), sizeof(word));
}

I tried to verify the correct size input on realloc function. I double verified inserted word_list elements. I think there is a lack of memory space somewhere between the word list elements but I can't figure out the pin.


Solution

  • This answer is based on the assumption that you do proper handling of your pointers between the part where you allocate memory for 1 element each and where you try to reallocate the memory.

    This part

    // realloc to correct size
    for(int a = 0; a < word_nb; a++) 
    {
        *(word_list + (word_nb-1)) = (char *)realloc(*(word_list + (word_nb-1)), sizeof(word));
    }
    

    can be written much more readable like this:

    // realloc to correct size
    for(int a = 0; a < word_nb; a++) 
    {
        word_list[word_nb-1] = realloc(word_list[word_nb-1], sizeof(word));
    }
    

    In this line you provide a wrong size. sizeof(word) is the size of the pointer, not the length of the content of your string.

    Assuming you enlarged the size allocated for word properly, you can use strlen(word)+1 to resize your buffer.