次のプログラムがあります。
#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);
}
}
基本的に、それぞれ異なる値を持つ 5 人の異なるプレイヤーを作成し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==
したがって、最初のプレーヤーを削除する私の方法は明らかに間違っています。メモリの問題なしに最初のプレーヤーを削除するにはどうすればよいですか?