这是《c++编程思想》上一个例子:#ifndef STACK_H_
#define STACK_H_class stack {
struct link {
void* data;
link* next;
link(void* Data, link* Next) {
data = Data;
next = Next;
}
} * head;
public:
stack() { head = 0; }
~stack();
void push(void* Data) {
head = new link(Data, head);
}
void* peek() const { return head->data; }
void* pop();
};
#endif#include <stdlib.h>
#include "H:\YA\STUDIO\12\12.2\12.2.3\stack.h"void* stack::pop() {
if (head == 0) return 0;
void* result = head->data;
link* oldHead = head;
head = head->next;
delete oldHead;
oldHead = 0;
return result;
}stack::~stack() {
link* cursor = head;
while (head) {
cursor = cursor->next;
delete head;
head = cursor;
}
}下面是测试程序:
#include "H:\YA\STUDIO\12\12.2\12.2.3\stack.h"
#include "H:\YA\STUDIO\12\12.2\12.2.1\strings.h"
#include <fstream.h>
#include <assert.h>void main(void)
{
ifstream file("test.cpp");
assert(file);
const bufsize = 100;
char buf[bufsize];
stack textlines; while(file.getline(buf, bufsize))
textlines.push(String::make(buf)); String* s;
while ((s = (String*)textlines.pop()) != 0)
cout << *s <<endl;
}结果和上说得一样,stack本身也没有做,分配得内存也不见了。
这是什么回事?
谢谢

解决方案 »

  1.   

    我的想法:
    stack分配的link内存没有泄漏;String::make(buf)的内存是pop返回的,你的测试程序中却没有释放,所以会泄漏。
      

  2.   

    我在测试程序得while语句改了一下
    while ((s = (String*)textlines.pop()) != 0)
    {
    cout << *s <<endl;
    delete s;
    s = 0;
    }可仍然是前面得问题。我进行跟踪调试发现pop()函数里得head值一开始是0,结果就跳了出来。????????????????????
      

  3.   

    因为没有你的Strings的源程序,所以不能帮你调试。你确信push执行了?并且参数正确?