1

我有以下程序:

#include <stdio.h>
#include <stdlib.h>

typedef struct a{
    int a;
} Player;

typedef struct b{
    Player players[5];
}* Formation;

int main()
{
    Player a; a.a = 1;
    Player b; b.a = 2;
    Player c; c.a = 3;
    Player d; d.a = 4;
    Player e; e.a = 5;

    Formation team = malloc(sizeof(*team));
    team->players[0] = a;
    team->players[1] = b;
    team->players[2] = c;
    team->players[3] = d;
    team->players[4] = e;

    for (int i = 0; i < 5; i++){
        team->players[i] = team->players[i + 1];
    }

    Player empty;
    team->players[4] = empty;
    for (int i = 0; i < 4; i++){
        printf("\n%d\n", team->players[i].a);
    }
}

本质上,我创建了五个不同的播放器,每个播放器都有不同的a值,然后将它们放入动态分配的 Formationplayers数组中。然后,我通过将数组中的所有值向左移动并在数组的最后一个元素中放置一个空玩家来移除第一个玩家。当我运行时,它会打印(如预期的那样)2345

但是当我valgrind在程序上运行时,我得到:

==25919== Invalid read of size 4
==25919==    at 0x4005DF: main (in /u1/023/sdkl1456/mtm/ex1/test/test)
==25919==  Address 0x4c22054 is 0 bytes after a block of size 20 alloc'd
==25919==    at 0x4A069EE: malloc (vg_replace_malloc.c:270)
==25919==    by 0x400589: main (in /u1/023/sdkl1456/mtm/ex1/test/test)
==25919== 

所以显然我删除第一个玩家的方法是不正确的。如何在没有内存问题的情况下删除第一个播放器?

4

1 回答 1

6
for (int i = 0; i < 5; i++){
    team->players[i] = team->players[i + 1];
}

您正在阅读最后一个元素,因为您的数组只有 5 个元素。

于 2013-11-05T19:38:22.903 回答