1

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 ?

1
  • 1
    You are invoking undefined behavior - it's "working" because your compiler's implementation happens to produce that kind of code (Which may just be coincidental, change with changes to the code, be different on a different compiler, change with optimization level, ....) Commented Dec 14, 2016 at 15:53

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

does this mean that my code is correct, because here I see a different syntax for the same task stackoverflow.com/questions/6169972/…
Your code is absolutely not correct. You can't access position 13 legally in a 10 element array.
Thank you ! This is what I needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.