我有以下程序:
#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
值,然后将它们放在动态分配的阵型players
数组中。然后我通过移动数组中的所有值并将空播放器放在数组的最后一个元素中来移除第一个播放器。当我跑步时,它打印(按预期)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==
显然我删除第一个玩家的方法不正确。如何在没有内存问题的情况下删除第一个播放器?
答案 0 :(得分:6)
for (int i = 0; i < 5; i++){
team->players[i] = team->players[i + 1];
}
您正在读取最后一个元素之外的元素,因为您的数组只有5个元素。