Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack around the variable ' ' was corrupted

Tags:

c++

void GameBoard::enterShips()
{
    char location[1];
    int ships = 0;
    int count = 1;

    while(ships < NUM_SHIPS)
    {
        cout << "Enter a location for Ship " << count << ": ";
        cin >> location;
        cout << endl;

        Grid[location[0]][location[1]] = SHIP;
        ships++;
        count++;
    }
}

Im writing a battleship game. I have the board layouts working and the computers randomly generated ships. Now I am working on this method to prompt the user to enter coordinates for the ships When I run the program, it allows me to enter 5 ships. When I enter the 6th ship, it gives me this error.

Stack around the variable location was corrupted.

Ive looked for answers online and have not found anything exclusive.

Any help would be appreciated.

like image 207
bluetickk Avatar asked Feb 27 '11 20:02

bluetickk


2 Answers

location is an array of a single char.
There is no location[1].

like image 177
SLaks Avatar answered Oct 11 '22 14:10

SLaks


You are prompting the memory address of location array to your user. You should ask location indices separately:

void GameBoard::enterShips()
{
    int location[2];
    int ships = 0;
    int count = 1;

    while(ships < NUM_SHIPS)
    {
        cout << "Enter a location for Ship " << count << ": ";
        cin >> location[0];
        cin >> location[1];
        cout << endl;

        Grid[location[0]][location[1]] = SHIP;
        ships++;
        count++;
    }
}

Notice int location[2]; since an array of size 1 can only hold one element. I also changed the element type to int. Reading char's from the console will result in ASCII values, which are probably not what you want.

like image 28
Tugrul Ates Avatar answered Oct 11 '22 12:10

Tugrul Ates