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 ?

4
  • 5
    undefined behavior means anything can happen Commented Dec 28, 2014 at 8:03
  • Common idiom is to use malloc first. Commented Dec 28, 2014 at 8:09
  • Try to use malloc, it will be the same thing. Commented Dec 28, 2014 at 8:22
  • Similar: stackoverflow.com/questions/27269265/… Commented Dec 28, 2014 at 11:57

2 Answers 2

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.

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

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.