Search code examples
cglibcrealloc

glibc detected: realloc(): invalid next size


I'm trying to create a dynamic array which stores the words of a given sentence in a dynamic 2-D array using a double pointer, but whenever I give more than three words, I get the following error:

*** glibc detected *** ./a.out: realloc(): invalid next size: 0x000000000255a030 ***

Relevant code below:

#include <stdio.h>
#include <stdlib.h>  
int main()  
{
    char **ptr=NULL;  
    char letter;    
    int ptrsize=1, wordsize=1;  
    ptr=malloc(ptrsize*sizeof(char *));
    ptr[ptrsize]=(char *)malloc(wordsize*sizeof(char));
    do
    {
            letter=getchar();
            while ((letter!=' ')&&(letter!='\n'))
            {
                    ptr[ptrsize][wordsize]=letter;
                    *ptr= realloc(*ptr,wordsize+1);
                    wordsize++;
                    letter=getchar();
            }
            ptrsize++;
            ptr = realloc(ptr,ptrsize*sizeof(char));
            wordsize=1;
            ptr[ptrsize]=malloc(wordsize*sizeof(char));
    }
    while (letter!='\n');
    return 0;
}

I have managed to increase the size of the sentence by making alterations to the malloc and realloc of the double pointer, but still haven't found any solid solution. Thanks in advance.


Solution

  • This code

     ptr=malloc(ptrsize*sizeof(char *));
     ptr[ptrsize]=(char *)malloc(wordsize*sizeof(char));
    

    And the similar lines repeated later in the loop body are incorrect.

    An array like

    Type* ptr = malloc(N * sizeof(Type));
    

    has valid indexes from 0 to N - 1. ptr[N] is always going to be past the end of the array. Writing to this memory and/or reallocing it is likely to end up corrupting the heap data structures.