c++ - 使用指向数组中元素的指针释放内存

标签 c++ pointers memory-management

我有以下 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 operator new(std::size_t) or operator new(std::size_t, constvstd::nothrow_t&) in the standard library ...

这里有几个问题。首先,如果你使用了 calloc,你应该使用 free

然后,您应该将您从 calloc 获得的指针传递给 free

calloc 将内存分配为一个连续的 block ,并且整个 block 都使用 free 释放,而不是它的一部分。

参见 http://www.cplusplus.com/reference/cstdlib/calloc/ .

关于c++ - 使用指向数组中元素的指针释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25299005/

相关文章:

C++ 对象构造有垃圾,为什么?

c++ - 将类对象初始化为引用内存

algorithm - 反转替代元素并附加到列表末尾

windows - 为什么操作系统不能使用整个 64 位进行寻址?为什么只有 48 位?

linux - Linux 上的可清除内存区域

c++ - (C++)如何在Window程序中使用虚函数?

c++ - 使用搅拌器处理图像 - OpenCV

c++ - std::set - 类似于我的容器中的函数对象支持

c - 接受并返回指针的函数指针

sql-server - SQL Server 事务,未提交的数据保存在哪里?