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);
    }
}

基本的に、それぞれ異なる値を持つ 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== 

したがって、最初のプレーヤーを削除する私の方法は明らかに間違っています。メモリの問題なしに最初のプレーヤーを削除するにはどうすればよいですか?

4

1 に答える 1

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

配列には5つの要素しかないため、最後の要素を1つ過ぎて読み取っています。

于 2013-11-05T19:38:22.903 に答える