0

Hey guys I start to programming c and I had one question about malloc. Malloc allocate memory. In my example I allocate memory for one integer. But I had enough memory for an int array with 3 ints. Why does it correct compile?

int *array=malloc(1*sizeof(int));

array[0]=1;
array[1]=2;
array[2]=3;
array[3]=4;
array[4]=5;

int i;
for(i=0;i<5;i++)    {
    printf("%d",array[i]);
}
  • Oops....`1*sizeof(int))` can hold only one int, not 5. – Paul Ogilvie Oct 31 '19 at 11:36
  • @BigLebowski 3 or 5 integers? – Vlad from Moscow Oct 31 '19 at 11:36
  • 1
    Because the compiler does not implement bounds checking. The behavior is undefined. The actual memory block may be bigger than what you requested or the memory after your allocated array may be currently unused, so you may or may not notice a problem at runtime. – Bodo Oct 31 '19 at 11:36
  • It _compiles_ corectly because the C compiler doesn't check your bounds. It probably will not _run_ correctly because you go out of array bounds, and the C runtime neither checks array bounds. – Paul Ogilvie Oct 31 '19 at 11:37
  • Undefined behavior. Don't go beyond your allocated memory. – Irelia Oct 31 '19 at 11:38
  • 1
    It *might* run correctly because C does not guarantee a failure if you break the rules. But just because it *can* sometimes work, doesn't mean it will *always* work. You park your car without the brake applied. Why didn't it roll away? *Should* it have rolled away? – Weather Vane Oct 31 '19 at 11:42
  • 1
    @PaulOgilvie I think that was the point of the question - not enough allocation, but 3 elements worked and 5 didn't. – Weather Vane Oct 31 '19 at 11:43
  • thanks for helping everybody this was my first question in stackoverflow and i am surprised how fast the community answer. –  Oct 31 '19 at 11:57
  • Welcome to the site! You might also benefit by taking the [tour](https://stackoverflow.com/tour). – Weather Vane Oct 31 '19 at 12:16

0 Answers0