【发布时间】:2010-08-16 11:45:08
【问题描述】:
问题:
我尝试释放由 STL 列表的指针项指向的内存。
这应该可以正常工作,但在我的情况下,列表中可能有重复的指针,即使我测试指针是否为 NULL,我也会得到一个双重 dealloc 异常(参见下面的源代码)。 我该如何解决这个问题?
环境:
- Debian5 莱尼
- gcc 版本 4.3.2 (Debian 4.3.2-1.1)
- libc-2.7.so
- libstdc++.so.6.0.10
- Eclipse Galileo 构建 ID:20100218-1602 / CDT。
C++源代码:
list<Line *> * l = new list<Line *>;
Line * line = new Line(10, 10, 10, 10);
l->push_back(line);
l->push_back(line);
cout << "line addr " << line << endl;
for (list<Line *>::iterator it = l->begin(); it != l->end(); it++)
{
if (*it != NULL)
{
cout << "line it " << *it << " " << (*it)->toString() << endl;
delete (*it);
(*it) = NULL;
}
}
l->clear();
错误显示:
*** glibc detected *** /home/debian/workspace/Scrap/Release/Scrap: double free or corruption (!prev): 0x0846de20 ***
======= Backtrace: =========
/lib/i686/cmov/libc.so.6[0xb6d68764]
/lib/i686/cmov/libc.so.6(cfree+0x96)[0xb6d6a966]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb6f402e1]
/home/debian/workspace/Scrap/Release/Scrap[0x8067cb0]
/lib/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb6d10455]
/home/debian/workspace/Scrap/Release/Scrap(_ZNSt8ios_base4InitD1Ev+0x49)[0x8052cd1]
======= Memory map: ========
08048000-0842c000 r-xp 00000000 08:01 3819374 /home/debian/workspace/Scrap/Release/Scrap
0842c000-08451000 rw-p 003e3000 08:01 3819374 /home/debian/workspace/Scrap/Release/Scrap
【问题讨论】:
-
为什么要存储指针?标准容器是为对象设计的。