Reputation: 149
I am defining a type of structures
typedef struct structs{
int freeSpace;
} structs;
I am creating a pointer to a structure
structs* arrayOfStructs;
I am allocating memory for array of size 5 of that structure
arrayOfStructs = malloc(5 * sizeof (arrayOfStructs));
arrayOfStructs[3].freeSpace = 99;
printf("\n%d", arrayOfStructs[3].freeSpace);
At some point I am reallocating that memory to array of size 10
arrayOfStructs = realloc(arrayOfStructs, 10 * sizeof (arrayOfStructs));
arrayOfStructs[8].freeSpace = 9;
printf("\n%d", arrayOfStructs[8].freeSpace);
And here I am setting freespace 17 at position 13 of the array which I expect to have only 10 positions.
arrayOfStructs[13].freeSpace = 17;
printf("\n%d", arrayOfStructs[13].freeSpace);
free(arrayOfStructs);
Why is this working ? What am I doing wrong ?
Upvotes: 1
Views: 258
Reputation: 234635
The behaviour of the program is undefined.
You are accessing memory that doesn't belong to you.
(What could well be happening is that realloc
is obtaining more memory from the operating system than is actually required).
Upvotes: 5