0

I am expecting NULL pointer exception but I am getting output 222. How is this working.

int main()
{
    int *p = (int*)malloc(0);
    *p = 222;
    cout << *p;
    return 0;
}
raj
  • 135
  • 1
  • 9

2 Answers2

2

The behaviour of your program is undefined.

The behaviour of malloc with 0 passed is implementation defined: it can return 0 or a pointer. If it returns a pointer, then you must pass that pointer to free, but you must not deference that pointer.

C and C++ do not differ in this respect.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
0

I am expecting NULL pointer exception

Your expectation is misguided.

Firstly, malloc is not guaranteed to retrurn a null pointer when allocating 0 size.

Secondly, indirecting a null pointer (or any pointer returned by malloc(0)) is not guaranteed to cause an exception. Instead the behaviour is undefined.

eerorika
  • 223,800
  • 12
  • 181
  • 301