有一个关于内存的问题,下面的代码我实现了一个动态数组(明显是python用习惯了qwq),这里面我实现了多维数组(用template),但好像new和calloc分配的内存我没有按照章程释放(相当于我只把多维数组的根的内存释放了好像,但他的子树没释放),在windows10系统下运行正常,但我怕别的系统会出问题,所以我想实现全释放(delete和free),搞了很久还是没有头绪 (鄙人不喜欢用debug,找bug都是硬翻qwq,所以关于内存的有点头大)
#include <iostream>
#include "../../sortion/sort.h"
template<typename type>
#define varName(variable) (#variable)
class Array{
private:
static const unsigned int extendSize;
type* array=(type*)calloc(20,sizeof(type));
unsigned long int arraySize=20;
long int top=-1;
void memoryUpdate(){
// std::cout<<"this->memorUpdate() "<<this<<std::endl;
type* buf=this->array;
this->array = (type*)calloc((this->arraySize+=this->extendSize),sizeof(type));
for(int i=0;i<this->arraySize;i++){
if(i<=this->top) this->array[i]=buf[i];
else{
type* b=new type();
this->array[i] = *(b);
}
}
free(buf);
}
void memoryUpdate(const unsigned int& a){
// std::cout<<"this->memorUpdate(const unsigned int&)"<<std::endl;
free(this->array);
this->top = -1;
this->array = (type*)calloc((this->arraySize=a),sizeof(type));
for(int i=0;i<this->arraySize;i++){
type* buf = new type();
this->array[i] = *(buf);
}
}
protected:
public:
Array(){
// std::cout<<"this->Array() , ptr="<<this<<std::endl;
for(int i=0;i<this->arraySize;i++){
type* buf = new type();
this->array[i] = *(buf);
}
};
Array(const unsigned int& Initlength){
this->memoryUpdate(Initlength);
}
~Array(){
free(this->array);
}
const unsigned int length()const{
return this->top+1;
}
Array copy() const{
return *this;
};
void foreach(void*(*func)(type&)){
for(int i=0;i<this->top+1;i++)func(this->array[i]);
};
void sort(){
hubire::sort::insert(this->array,this->top+1);
};
void extend(Array& ){
};
void extend(type*){
}
void extend(const unsigned int& size);
void push(type element){
if(++this->top>=this->arraySize) this->memoryUpdate();
this->array[this->top]=element;
};
void push(){
if(++this->top>=this->arraySize) this->memoryUpdate();
type *buf = new type();
this->array[this->top]=*buf;
}
void insert(const unsigned int& pos,type element){
if(this->top==-1) return;
if(this->top+1>=this->arraySize) this->memoryUpdate();
for(int i=this->top;i>=pos;i--){
this->array[i+1] = this->array[i];
}
this->array[pos]=element;
};
type pop(){
return this->array[this->top--];
};
type& operator[](const int& ptr){
return this->array[ptr];
}
};
template<typename type>
const unsigned int Array<type>::extendSize=5;
// #endif
int main(){
Array<int> array; //这里和下面可以忽略,只是调试
for(int i=0;i<900;i++){
array.push(hubire::sort::out::Random::random()*50);
printf("%d ",array[i]);
}
putchar('\n');
putchar('\n');
putchar('\n');
array.sort();
putchar('\n');
putchar('\n');
putchar('\n');
for(int i=0;i<20;i++){
// array.push(hubire::sort::out::Random::random()*50);
printf("%d ",array[i]);
}
}