I'm having a lot of trouble getting my head around something which seems deceptively simple. Basically I'm trying to get a string of user input from the keyboard using getchar(), and put that into an array. If the input exceeds the default size of the array, I'm attempting to dynamically grow the array using realloc(). The code compiles, but when I then look at the values stored in the array, it spits out bizarre numbers. Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
while(1)
{
currentChar = getc(stdin);
if(currentChar < '0' || currentChar > '9') //if the char entered by user is non-numerical, break
{
break;
}
charList[i] = currentChar;
i++;
if(i > DEFAULT_CHAR_NUM) // if i > array size, dynamically allocate more mem to array.
{
charList = (char*) realloc(charList, i*sizeof(char)); //realloc is the problem?
}
}
edit: It might also be worth mentioning that I only get "bizarre values" when I enter a string larger than DEFAULT_CHAR_NUM.
At my wits end on this, so any help would be appreciated.
In order to use realloc() as you're using it, charList must essentially be a char*
that was dynamically allocated prior to the while loop. For example:
1 2 3 4 5 6 7
// You could use malloc( DEFAULT_CHAR_NUM ) instead
char* charList = static_cast<char*>( calloc( DEFAULT_CHAR_NUM, sizeof( char ) ) );
char currentChar;
while( 1 ) {
...
}
As a matter of efficiency, your code grows the array by 1 character at a time, which
means potentially a lot of reallocations. I'd recommend growing it by some other
increment: