0

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

James Franco
  • 4,516
  • 10
  • 38
  • 80

1 Answers1

0

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.

Djee
  • 429
  • 3
  • 9
  • Very wild indeed as compared to c++ – James Franco Nov 10 '16 at 07:38
  • Thank you for down voting my answer! Don't know why, still. – Djee Nov 10 '16 at 07:42
  • I did not downvote it. However I am upvoting as I would like a reason for the downvote incase you were wrong – James Franco Nov 10 '16 at 07:42
  • Not you James! Somebody very funny. I read the question again against my answer. Well, that's life to see weird behaviors like this. Back to your comment, C++ is not inherently safer: safer only if you don't use C constructs in it! Which means knowing C and its many caveats and dangers before. – Djee Nov 10 '16 at 07:49
  • Accessing an array out of bounds is undefined behavior. Your answer incorrectly states that there is nothing wrong with that. – 2501 Nov 10 '16 at 08:02