开发者

Allocating memory by size zero in c++?

int a = 10;
int *p = new int[0];

p = &a;
cout << *p << endl;

In c++, what happens if allocate memory size by zero?

after allocation I get valid memory pointer, and prints valid number.

But I think new operator should return something like FAILD or NULL.

Can anybody explain detail?开发者_如何学Go


after allocation I get valid memory pointer, and prints valid number.

Your provided code doesn't actually test this.

When you do p = &a, you're reassigning p to point somewhere completely different. Whatever it held before is irrelevant to the continued execution of the program.


In c++, what happens if allocate memory size by zero?

A zero sized array is valid.
You just can de-reference any members.

This is why the Greeks spent such a long time debating it thinking about zero as a number. But we can thank India at its great minds for eventually bringing zero as a number 0. It took them forever and aren't we glad they did, a lot of modern maths would not be possible without such a unique value.

after allocation I get valid memory pointer,

That is correct.
If it failed it would throw an exception.

and prints valid number.

Your assignment: p = &a; is probably not what you want. As this just leaks memory and set p to point at the variable a. What you were probably trying to do is:

(*p) = a;
// or
p[0] = a;

This is undefined behavior.
As you are assigning to values after the end of the array.

But I think new operator should return something like FAILD or NULL.

No.

Can anybody explain detail?

Yes.


You assign the pointer "p" at the chunk of "a" so p doesn't point to the zero size chunk anymore when you print it.


From ISO/IEC 14882:2003(E), 5.3.4.6

Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enu- meration type (3.9.1) with a non-negative value. [Example: if n is a variable of type int, then new float[n][5] is well-formed (because n is the expression of a direct-new-declarator), but new float[5][n] is ill-formed (because n is not a constant-expression). If n is negative, the effect of new float[n][5] is undefined.]

They are intelligent. Can zero be considered as non-negative value ? Might be yes, since it is compiling with no problems, I guess.


From ISO/IEC 14882:2003(E), 5.3.4.7

When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

So you get a valid pointer, but you can't dereference it, and must still delete[] it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜