Question

This program strictly reads only alphabets, and pushes back to the vector as so. However the text file is just like any other text file.

I have encountered this STD bad alloc exception and is as follows.

char keyArray[5][5];

keyArray[0][1] = 'a';
keyArray[0][2] = 'b';
keyArray[0][3] = 'c';
keyArray[0][4] = 'd';
keyArray[0][5] = 'e';
keyArray[1][1] = 'f';
keyArray[1][2] = 'g';
keyArray[1][3] = 'h';
keyArray[1][4] = 'i';
keyArray[1][5] = 'k';
keyArray[2][1] = 'l';
keyArray[2][2] = 'm';
keyArray[2][3] = 'n';
keyArray[2][4] = 'o';
keyArray[2][5] = 'p';
keyArray[3][1] = 'q';
keyArray[3][2] = 'r';
keyArray[3][3] = 's';
keyArray[3][4] = 't';
keyArray[3][5] = 'u';
keyArray[4][1] = 'v';
keyArray[4][2] = 'w';
keyArray[4][3] = 'x';
keyArray[4][4] = 'y';
keyArray[4][5] = 'z';


ifstream readFile;
vector<char> paddedVector;
char c;
int number_of_chars = 0;
readFile.open ("test.txt", ifstream::in);
while(  !readFile.eof() )
{
    if(readFile.peek() == -1)
        break;
    c = readFile.get();
    if(!isalpha(c))
        continue;

    if(c != '\n') //bad alloc here
    {
        ++number_of_chars;
        paddedVector.push_back(c); //std bad alloc happens here
    }
}

Please kindly advise.

EDIT When i took away the keyArray portion, it works fine. why is it so? what am i doing it incorrectly here?

Was it helpful?

Solution

Your problem are the following 5 lines:

keyArray[?][5] = '?';

where you are indexing out of the boundaries of your keyArray array. It has probably overwritten an internal pointer in the paddedVector object. In turn when the vector tries to (re)allocate memory, you get this exception because delete[] cannot understand where that address came from.


Note that for the same reason you started your first index from 0, you should also start your second index from 0! Therefore, both indices should be in the range [0, 5).

OTHER TIPS

char keyArray[5][5];
// ...
keyArray[4][5] = 'z';

The above writes beyond the end of the array. Valid indexes for keyArray are keyArray[0..4][0..4]. Your program is in undefined behaviour land.

You are incorrectly addressing the inner arrays. They are also 0 based, so the format should be

keyArray[0][0] = 'a'
.
.
.
keyArray[4][4] = 'z'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top