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

p[0]=2;

p[1]=3;

In windows OS , in visual studio I am executing above code.

I allocated memory for only one item but I am able to assign value to second item? How it is possible? How to restrict it?

I am not getting any compiler error.

user369287
  • 692
  • 8
  • 28
  • 2
    It's undefined behavior, so there's no telling what happens. Most likely you just get memory corruption, perhaps an access violation. *"How to restrict it?"* By not doing it. Maybe your compiler or a static code analyzer can give you a warning. – Blaze Apr 26 '19 at 09:46
  • 3
    C have no boundary checking at all (not even for actual arrays). It's your responsibility as a programmer to make sure you don't go out of bounds. – Some programmer dude Apr 26 '19 at 09:47
  • Also please read [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/440558) – Some programmer dude Apr 26 '19 at 09:48

2 Answers2

2

This is called Undefined Behavior. You have allocated an array of ints of size 1. Accessing memory locations beyond allocated space is undefined behavior. This means that the compiler is free to do what it wants from that point on. It could throw an error, or make the program crash at runtime, or anything else.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
DarkAtom
  • 2,589
  • 1
  • 11
  • 27
1

In the C programming language you have a direct memory access. Also, in the performance reasons there is no any index checking for arrays, null-pointer checking etc. For restrict it, you may have to implement your own checking for the index.

alexzok
  • 81
  • 7