James Franco James Franco - 1 year ago 59
C Question

Why am I not getting a memory exception here

Suppose I have this data structure

struct foo{
int a;
int b;

Now I would like to create an array of 2 items . So I do this

struct foo* farry = (struct foo*) malloc(2 * sizeof(struct foo));

Please correct me if I am wrong the above would create 2 slots having foo structure default initialized ? Is that correct ? If so then If i do this

struct foo* farry = (struct foo*) malloc(2 * sizeof(struct foo));
farry[0].a =1;
farry[1].a =2;
farry[2].a =3;
farry[3].a =4;
farry[4].a =5;
for(i=0 ; i<=4 ; i++)
printf("Value %d \n",farry[i].a );

Then why does at
farry[2].a =3
it not tell me that a memory error occured. Instead it simply prints 1,2,3,4,5

Answer Source

You simply access uncontrolled locations in your heap which is in the program and user space. Nothing wrong from this point of view so no memory error.

Simply you're messing with other static variables in the heap. Should you mess too much like this your program would crash (for example if your messing for some reason reaches the program stack or a variable being messed will make a loop wreak havoc). Yes C is wild is this respect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download