Problem with realloc

From: Daniel Chirillo (danchirillo_at_yahoo.com)
Date: 08/05/04


Date: Wed, 04 Aug 2004 22:45:25 GMT

I'm playing around with dynamic arrays of strings. Can anyone offer an
explanation as to why the realloc in this code is crashing the program? For
now, ignore the fact that I'm leaking memory.

const int MAX_STR_LENGTH = 256;
char **array = (char **)malloc( sizeof(char*) * 1);
char *input = (char*)malloc(MAX_STR_LENGTH * sizeof(char));

 size_t length = -1;
 int i;

 while(-1) {

       length++;
       printf("Enter: ");
       scanf("%s", input);

       if( strcmp( "-1", input) == 0 ) break;
       array = (char **)realloc(array, length); /* the problematic line */

       array[length] = (char*)malloc(MAX_STR_LENGTH + 1);

       strcpy( array[length], input);

  }

  for(i = 0; i < length; ++i ) {
      printf("%s\n", array[i]);
  }



Relevant Pages

  • Re: Problem with realloc
    ... > I'm playing around with dynamic arrays of strings. ... > explanation as to why the realloc in this code is crashing the program? ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Guitar intonation problem?
    ... Thanks for your explanation of how it works. ... Actually, old strings go out of intonation because, either: ... Therefore the string vibrations decay to ... the smart-ass outrageous explanation routine. ...
    (alt.guitar.bass)
  • Re: passing pointers [C]
    ... >I could malloc some space, concatenate the first two, malloc some more, ... >strings, do that malloc, and return a new string. ... Since you only call realloc, there is no way for old allocations not ...
    (alt.comp.lang.learn.c-cpp)
  • Re: K&R2 Secition 5.9 - major blunders
    ... Each element of b doesn't point to a 20 element array of int. ... This mistake is crucial because ... my explanation is really the qualities of something else: ... > The use of the array of pointers is to store the strings. ...
    (comp.lang.c)
  • Re: K&R2 Secition 5.9 - major blunders
    ... Each element of b doesn't point to a 20 element array of int. ... This mistake is crucial because ... my explanation is really the qualities of something else: ... > The use of the array of pointers is to store the strings. ...
    (comp.lang.c)