我正在学习创建指针数组并释放内存。这是我的简单代码
#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)
我的问题是,为什么我收到了消息&#34;无效的免费()/删除/删除[] / realloc []&#34; ?以及如何解决它?
谢谢,
答案 0 :(得分:0)
在这个循环中
for (int i = 0; i < 5; i++) {
classroom[i] = &i;
cout<<*classroom[i]<<endl;
}
你正在摧毁阵列的内存。您将所有指针设置为i
的地址,然后当for循环结束时i
被销毁,您现在有悬空指针。试图删除它们是未定义的行为。
答案 1 :(得分:0)
classroom[i] = &i;
应该是:
*classroom[i] = i;
您将使用new
分配的指针替换为局部变量i
的地址。然后,您稍后尝试删除该指针,但您不能删除局部变量,只能删除使用new
分配的变量。您实际想要做的是将i
的值复制到动态分配的变量中。
答案 2 :(得分:0)
我认为问题在于,当您delete
每个classroom
时,它不再指向由int
创建的new
的原始记忆位置,因为您是没有将i
的值推到classroom[i]
的内存位置,实际上您正在将classroom[i]
更改为指向i
的内存位置。
尝试更改
classroom[i] = &i;
到
*(classroom[i]) = i;