C++ new int[0] — will it allocate memory?

前端 未结 6 1848
無奈伤痛
無奈伤痛 2020-11-22 06:16

A simple test app:

cout << new int[0] << endl;

outputs:

0x876c0b8

So it looks like it works.

6条回答
  •  名媛妹妹
    2020-11-22 06:49

    Yes it is completely legal to allocate a 0 sized block with new. You simply can't do anything useful with it since there is no valid data for you to access. int[0] = 5; is illegal.

    However, I believe that the standard allows for things like malloc(0) to return NULL.

    You will still need to delete [] whatever pointer you get back from the allocation as well.

提交回复
热议问题