删除[]指针数组无效

Invalid delete[] array of pointer

本文关键字:数组 无效 指针 删除      更新时间:2023-10-16

我正在学习创建指针数组并释放内存。这是我的简单代码

#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被销毁,现在就有了悬空指针。试图删除它们是未定义的行为。