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.