我有以下 C++ 代码:
int main(){
unsigned char *abc = (unsigned char *)calloc(100,1);
unsigned char *def = &abc[50];
delete def;
}
这会释放调用 calloc 分配的所有内存,还是只释放从 def
指向的内存位置开始的内存?
最佳答案
这是未定义的行为。撞车,如果你幸运的话。
根据 C++ 标准(工作草案,N3291=11-0061)
3.7.4.2 Deallocation functions [basic.stc.dynamic.deallocation]
...
The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the behavior is undefined if the value supplied to operator
delete(void*)
in the standard library is not one of the values returned by a previous invocation of either operatornew(std::size_t)
or operatornew(std::size_t, constvstd::nothrow_t&)
in the standard library ...
这里有几个问题。首先,如果你使用了 calloc
,你应该使用 free
。
然后,您应该将您从 calloc
获得的指针传递给 free
。
calloc
将内存分配为一个连续的 block ,并且整个 block 都使用 free
释放,而不是它的一部分。
关于c++ - 使用指向数组中元素的指针释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25299005/