删除[]指针数组无效
Invalid delete[] array of pointer
我正在学习创建指针数组并释放内存。这是我的简单代码
#include <iostream>
using namespace std;
int main()
{
int* classroom[5];
for (int i = 0; i < 5; i++) {
classroom[i] = new int;
}
for (int i = 0; i < 5; i++) {
classroom[i] = &i;
cout<<*classroom[i]<<endl;
}
for (int i = 0; i < 5; i++) {
delete classroom[i];
}
return 0;
}
当我运行valgrind检查内存泄漏时,结果如下
==2868== Memcheck, a memory error detector
==2868== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==2868== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==2868== Command: ./m
==2868==
0
1
2
3
4
==2868== Invalid free() / delete / delete[] / realloc()
==2868== at 0x402ACFC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2868== by 0x8048700: main (in /home/student/Downloads/demo/m)
==2868== Address 0xbea69244 is on thread 1's stack
==2868==
==2868==
==2868== HEAP SUMMARY:
==2868== in use at exit: 20 bytes in 5 blocks
==2868== total heap usage: 5 allocs, 5 frees, 20 bytes allocated
==2868==
==2868== LEAK SUMMARY:
==2868== definitely lost: 20 bytes in 5 blocks
==2868== indirectly lost: 0 bytes in 0 blocks
==2868== possibly lost: 0 bytes in 0 blocks
==2868== still reachable: 0 bytes in 0 blocks
==2868== suppressed: 0 bytes in 0 blocks
==2868== Rerun with --leak-check=full to see details of leaked memory
==2868==
==2868== For counts of detected and suppressed errors, rerun with: -v
==2868== ERROR SUMMARY: 5 errors from 1 contexts (suppressed: 0 from 0)
我的问题是,为什么我收到的消息"invalid free()/delete/delete[]/realloc[]" ?如何解决?
谢谢,
classroom[i] = &i;
应:*classroom[i] = i;
你用局部变量i
的地址替换了你用new
分配的指针。然后你稍后尝试删除该指针,但是你不能删除局部变量,只能删除用new
分配的变量。您实际要做的是将i
的值复制到动态分配的变量中。
我认为问题在于,当您delete
每个classroom
时,它不再指向new
创建的int
的原始内存位置,因为您没有将i
的值推入classroom[i]
的内存位置,您实际上将classroom[i]
更改为指向i
的内存位置。
尝试更改
classroom[i] = &i;
*(classroom[i]) = i;
在这个循环中
for (int i = 0; i < 5; i++) {
classroom[i] = &i;
cout<<*classroom[i]<<endl;
}
你正在破坏数组的内存。将所有指针指向i
的地址,然后当for循环结束时,i
被销毁,现在就有了悬空指针。试图删除它们是未定义的行为。
相关文章:
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 数组下标的类型"float*[float]"无效
- 错误:数组下标的类型"int[int]"无效
- "错误:数组下标的无效类型'float [10001][float]'是什么意思?
- 错误:数组下标的类型"const bool[int]"无效
- 正在使用C 三元运算符中的字符串常数,一种无效的非效率数组的使用
- 数组下标编译的无效类型'int[int]'由于 -Wfatal 错误而终止
- 如何使用ISTream对象输入多个字符到对象的数组中?(and 0作为哨兵值.下面的我的代码将无效)
- 数组下标的无效类型INT [INT]
- 获取数组类型的无效错误
- 在结构中访问数组时无效使用非静态数据成员
- 从 c++ 中的函数对 2d 数组的转换无效
- Valgrind 显示无效的读/写错误,但我不使用 new 或 calloc,只使用向量和固定数组
- 当函数调用时,试图阻止数组更改时发生无效转换错误
- 使用多线程处理对象数组 - 无效使用 void 表达式错误
- 打印带有字符串的std::数组无效
- 将指针设置为等于2d数组-无效的数组分配
- 删除[]指针数组无效
- 用常量初始化数组无效
- 如何使数组无效