读书人

int* p = new int[0];会不会分配内存

发布时间: 2012-03-03 15:33:04 作者: rapoo

int* p = new int[0];会不会分配内存??
同样还有malloc(0);
我在vc6下测了malloc

====================
void* p=0;
p = malloc(0);
====================
p在malloc之后被赋了一个地址。
但是我不清楚有没有内存被分配?
哪位知道的能给讲讲吗?


[解决办法]
这个,你可以下载C和C++标准,自己在上面搜。标准对此有规定。
new int[0]肯定分配内存。
malloc的忘了,自己查吧。
[解决办法]
分配,在vc中,
int* p = new int[0];
得到内存内容FD FD FD FD;
int* p = new int[1];
为:CD CD CD CD FD FD FD FD;
int* p = new int[2];
为:CD CD CD CD CD CD CD CD FD FD FD FD;
[解决办法]
在标准C++中new int[0]这样的语句是不会通过编译的,编译器会指出这是一个错误。

[解决办法]
摘自C99标准:7.20.3 Memory management functions

If the size of the space requested is zero, the behavior is implementation-defined:
either a null pointer is returned, or the behavior is as if the size were some
nonzero value, except that the returned pointer shall not be used to access an object.
从上面的规定可以看出 malloc(0) 不一定能分配到空间。

摘自C++标准:
Even if the size of
the space requested is zero, the request can fail. If the request succeeds,the value returned shall be a nonnull
pointer value (4.10) p0 different from any previously returned value p1, unless that value p1 was subsequently
passed to an operator delete. The effect of dereferencing a pointer returned as a request for
zero size is undefined.

读书人网 >C++

热点推荐