有关堆损坏的错误

时间:2012-10-03 12:47:53

标签: c++ heap-corruption

我写了一个C ++程序,实际上它是一个游戏。 我收到了这个错误:

  

Windows已经在bla bla中触发了一个断点......

有人可以帮助我吗? 这是代码,但错误发生在AAA线上:

void r_motions(char **map,int size)
{
    int parameter_i,parameter_j,player_i,player_j;
    int *r_location_i = new int[1],*r_location_j = new int[1];
    player_finder(map,size,player_i,player_j);
    int r_num = robots_finder(map,size,r_location_i,r_location_j);
    for(int i=1;i<=r_num;i++)
    {
        parameter_i =0;
        parameter_j =0;
        if(r_location_i[i]>player_i) parameter_i = -1;
        if(r_location_i[i]<player_i) parameter_i =  1;
        if(r_location_j[i]>player_j) parameter_j = -1;
        if(r_location_j[i]<player_j) parameter_j =  1;
        map[r_location_i[i]][r_location_j[i]] = '.';
        r_location_i[i] = r_location_i[i]+parameter_i;
        r_location_j[i] = r_location_j[i]+parameter_j;
    }
    for(int i=1;i<=r_num;i++)
    {
        switch (map[r_location_i[i]][r_location_j[i]])
        {
        case '.': 
            map[r_location_i[i]][r_location_j[i]] = '+';
            break;
        case '@': 
            map[r_location_i[i]][r_location_j[i]] = '+';
            print_map(map,size);
            cout << "Robots win ." << endl;
            sleep(1000);
            exit(1);
            break;
        case '+':
            map[r_location_i[i]][r_location_j[i]] = '*';
            break;
        case '*': 
            map[r_location_i[i]][r_location_j[i]] = '*';
            break;
        default: cout << "what r u doin' ??";
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

好吧,对初学者来说,看看这个:

int *r_location_i = new int[1], ...;
...
for(int i=1;i<=r_num;i++)
  {
    parameter_i =0;
    ...
    if(r_location_i[i]>player_i) parameter_i = -1; // reading outside the array
    ...
    r_location_i[i] = r_location_i[i]+parameter_i; // writing outside the array
    ...
  }

返回并研究数组。 在您确切知道上述代码的错误之前,请不要触摸另一个指针