Problem with realloc
From: Daniel Chirillo (danchirillo_at_yahoo.com)
Date: 08/05/04
- Next message: Daniel Chirillo: "Re: Problem with realloc"
- Previous message: Niklas Borson: "Re: Contest: Overly complicated Hello.cpp"
- Next in thread: Daniel Chirillo: "Re: Problem with realloc"
- Reply: Daniel Chirillo: "Re: Problem with realloc"
- Reply: Josh Sebastian: "Re: Problem with realloc"
- Reply: Francis Glassborow: "Re: Problem with realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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]);
}
- Next message: Daniel Chirillo: "Re: Problem with realloc"
- Previous message: Niklas Borson: "Re: Contest: Overly complicated Hello.cpp"
- Next in thread: Daniel Chirillo: "Re: Problem with realloc"
- Reply: Daniel Chirillo: "Re: Problem with realloc"
- Reply: Josh Sebastian: "Re: Problem with realloc"
- Reply: Francis Glassborow: "Re: Problem with realloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|