我有一个结构
#ifndef EVENT_H
#define EVENT_H
struct Event {
int ID;
int num;
int * energies;
};
#endif
和一个与Event结构一起使用的函数,
#include <fstream>
#include "Event.h"
#include <iostream>
using namespace std;
Event * read(std::ifstream& os, Event * ev)
{
if(os.fail()) return NULL;
os >> ev->ID >> ev->num;
ev->energies = new int[ev->num];
if(ev->ID!=0 && ev->num!=0){
for (int i = 0; i < ev->num; ++i)
{
os >> * (ev->energies+i);
}
}
return ev;
}
这是main.cpp
#include <iostream>
#include <fstream>
#include "Event.h"
using namespace std;
Event * read(ifstream& os, Event * ev);
void dump(const Event& ev);
void clear(Event * ev);
int main(int argc, char const *argv[])
{
ifstream os(argv[1]);
Event * ev = new Event;
cout << "Created " << ev << endl;
Event * pointer=read(os, ev);
while(pointer!=NULL)
{
dump(*ev);
clear(ev);
Event * ev = new Event;
pointer = read(os,ev);
}
return 0;
}
我的问题是:在这种情况下,为什么在每次调用read()函数时都没有释放内存(在read()中用ev->energies = new int[ev->num];
分配)?
答案 0 :(得分:2)
不,内存未被释放。在函数结束时,您需要调用
delete [] ev->energies
答案 1 :(得分:0)
您的印象是分配的指针在超出范围时将被删除。事实并非如此。它会泄漏内存。此示例将突出显示您在评论中提供的代码中缺少的内容:
#include <iostream>
using namespace std;
int* read(int *array) {
int i=0;
int num=200;
array = new int[num];
cout << "Newly allocated pointer " << array << endl;
if(num==0) return NULL;
while(i<num) {
array[i] = i*i;
i++;
}
return array;
}
int main(int argc, char const *argv[])
{
int *ptr;
cout << "Original pointer address " << ptr << endl;
int *n = read(ptr);
cout << "Last value in allocated pointer " << n[199] << endl;
cout << "Allocated pointer address " << n << endl;
cout << "Original pointer address " << ptr << endl;
// following line can cause a segmentation fault
// cout << "Last value in original pointer (actually garbage) " << ptr[199] << endl;
delete[] n; // really should delete it
}
read()中的*数组按值传递,因此更改它将是本地范围。