1

I use this code in order to dynamically allocate more memory into my Struct array (mystructs), by increasing the size of size and reallocating memory:

int size = 1;   
MyStruct *mystructs = NULL;
MyStruct *tmp = NULL;
tmp = realloc(mystructs, sizeof(MyStruct) * size);
mystructs = tmp;

My question is that, even if i use size = 1 it still allocates way more memory than needed for that size, because when i start printing out struct values with printf(), then i can usually print out a few hundred array elements although it is supposed to contain only 1 element. Printing out means calling something like: printf("%d", mystructs[i].value);. Why can i be a value of about a few hundred, before it finally segfaults, because i accessed memory i wasn't supposed to ?

user3796577
  • 109
  • 1
  • 8

2 Answers2

2

Because it's undefined behavior to read beyond the allocated space and hence it will not always behave exactly the same, it is possible to read beyond the allocated space, but it's not correct.

And sometimes a segmentation fault will happen.

That is why you can keep reading with no problem, and suddenly segmentation fault.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
2

Being able to read memory doesn't mean you are allowed to do this.

It might be, as others pointed out, that the library just gets more memory from the OS than needed.

But it may as well be that it just uses memory that sits before other parts of memory used for something else.

So, even if you can read it, you shouldn't, because you never know. And, most important: don't write there - there may be other variables used by your program!

glglgl
  • 89,107
  • 13
  • 149
  • 217