简体   繁体   中英

Malloc and Realloc array of structs

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 ?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM