内存分配不当? [英] Improper de-allocation of memory?
问题描述
在测试我的代码时,由于类的测试平台始终指出,在使用new []分配的数组上调用delete时,始终会遇到有关使用delete的错误.我在〜IntVector中删除了两个扩展函数,其中Expand函数在为动态分配的数组重新分配内存的同时扩展容量.
如何正确使用Delete来防止内存泄漏并解决此错误?
主文件
#include"IntVector.h"#include< iostream>#include< vector>使用命名空间std;IntVector ::〜IntVector(){delete []数据;}无效IntVector :: expand(){上限=上限* 2;int * data2 =数据;数据=新的int [cap];数据=数据2;删除数据2;delete [] data2;}IntVector :: expand(unsigned amount){上限=金额;int * data2 =数据;数据=新的int [cap];数据=数据2;删除数据2;delete [] data2;}
标题
<代码> #ifndef INTVECTOR_H#define INTVECTOR_H使用命名空间std;类IntVector {私人的:未签名的sz;未签名的上限;int *数据;私人的:void expand();void expand(unsigned amount);};#万一
使用 new []
进行分配时,必须使用 delete []
.您的 expand
函数使用普通的 delete
.它还包含一些其他错误(重新分配指针,重复删除等).
您的复制构造函数在哪里?复制分配运算符?您可能需要阅读三个规则.>
When testing my code, I consistently get errors regarding the use of delete as my class's testbed states that delete is being called on an array allocated with new[]. I have delete in my ~IntVector and two expand functions with the expand functions expanding the capacity while reallocating memory for a dynamically allocated array.
How do I use delete correctly to prevent memory leaks and resolve this error?
main file
#include "IntVector.h"
#include <iostream>
#include <vector>
using namespace std;
IntVector::~IntVector(){
delete[] data;
}
void IntVector::expand(){
cap = cap * 2;
int *data2 = data;
data = new int[cap];
data = data2;
delete data2;
delete[] data2;
}
void IntVector::expand(unsigned amount){
cap = amount;
int *data2 = data;
data = new int[cap];
data = data2;
delete data2;
delete[] data2;
}
header
#ifndef INTVECTOR_H
#define INTVECTOR_H
using namespace std;
class IntVector{
private:
unsigned sz;
unsigned cap;
int *data;
private:
void expand();
void expand(unsigned amount);
};
#endif
When allocating with new[]
you have to use delete[]
. Your expand
function uses plain delete
. It also contains some other errors (reassigning pointers, double deletion, etc.).
And where's your copy-constructor? Copy-assignment operator? You might want to read about the rule of three.
这篇关于内存分配不当?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!