1

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.

macfij
  • 3,093
  • 1
  • 19
  • 24
SGuard
  • 23
  • 1
  • 5
  • possible duplicate of [Facing an error "\*\*\* glibc detected \*\*\* free(): invalid next size (fast)"](http://stackoverflow.com/questions/2317021/facing-an-error-glibc-detected-free-invalid-next-size-fast) – Jonathan Leffler May 14 '14 at 06:11

1 Answers1

2

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.

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78