Help with variable length arrays(malloc & realloc)

Hi.

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.
Last edited on
How is charList declared?

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
size_t arraySz = DEFAULT_CHAR_NUM;
char* charList = 0;
size_t charsRead = 0;

while( 1 ) {
    char ch = getc( stdin );
    if( ch < '0' || ch > '9' )
         break;

    if( charsRead == arraySz ) {
         arraySz += 100;  // Some incremental value
         charList = static_cast<char*>( realloc( charList, arraySz ) );
    }

    charList[ charsRead++ ] = ch;
}

However, since this _is_ a C++ forum/website, why not just:

[code]
unsigned int val = 0;
cin >> val;


since you are obviously trying to read non-negative integral values.
Oops, code above (in last block) doesn't quite work.
Change the first line to:

 
size_t arraySz = 0;

Topic archived. No new replies allowed.