shirazy
shirazy

Reputation: 109

I get the error which i cant fix : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped)

I used 2D dynamic array and I dont know how to fix the error, please help me! I wanna get a string from user and separate it to some string and put them into the 2d dynamic array. its the part of code where I allocate the array.

    int colCount,rowCount;
    string** table = new string*[rowCount];
    for(int i = 0; i < rowCount; ++i)
    {
    table[i] = new string[colCount];
    }

Upvotes: 0

Views: 854

Answers (1)

gsamaras
gsamaras

Reputation: 73384

Your code does not initialize colCount and rowCount, thus their values are garbage. You try to dynamically allocate memory with uninitialized variables, which, of course, invokes Undefined Behavior.

Initialize your variables, like:

int colCount = 5, rowCount = 5;

PS: Since this is C++, I suggest you use std::vector as a 2D array, like this for example:

std::vector<std::vector<std::string>> table;

Upvotes: 2

Related Questions