Reputation: 2974
I have the following program:
#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);
}
}
In essence, I create five different players, each with a different a
value, then put them inside a dynamically allocated Formation's players
array. I then remove the first player by shifting all the values in the array left and placing an empty player in the last element of the array. When I run, it prints (as expected) 2345
.
But when I run valgrind
on the program, I get:
==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==
So apparently my method of removing the first player is incorrect. How can I remove the first player without memory issues?
Upvotes: 1
Views: 1568
Reputation: 145829
for (int i = 0; i < 5; i++){
team->players[i] = team->players[i + 1];
}
You are reading one past the last element as your array has only 5 elements.
Upvotes: 6