Help with the implementation. I tried to create a class with a dynamic array. so that you can add items to the end.

class DynArray { private: int size; double *mass; public: DynArray() : size(0), mass(0) {} void add(const double &num) { double *p=new double[size+1]; memcpy(p,mass,sizeof(double)*size); p[size]=num; delete[] mass; mass=p; size++; } double get(const int &n) { return mass[n]; } ~DynArray(){delete[] mass;} }; 

This code is completely working, I'm wondering if there is any memory leak anywhere?

  • It is better to explain how you have this code compiled at all, without mass declaration. and memcpy is likely to be faster than the cycle and the main thing is shorter. And your second cycle will go beyond the bounds of the p array, since size you increased by 1 - Mike
  • This is a class method - j6wj1997
  • And by the way, why is there a second cycle at all? it seems to me double *p=new double[size+1]; memcpy(p,mass,sizeof(double)*size); p[size]=num; delete[] mass; mass=p; size++; double *p=new double[size+1]; memcpy(p,mass,sizeof(double)*size); p[size]=num; delete[] mass; mass=p; size++; as it is easier and shorter ... - Mike
  • what does memcpy mean what does it do? - j6wj1997
  • copies the memory area of ​​the specified size. those. it is completely identical to your first cycle. copies content of mass to p - Mike

1 answer 1

There are no leaks - you correctly use RAII: everything that you select is released in the destructor. There are a couple of small notes - for example, what's the point in the transfer

 add(const double &num) 

Easier and with the same effect to transfer just double .

And - it is very inefficient to constantly allocate / free memory with each addition. So you get O(n) selection / release per element. If, say, double each time an overflow occurs, the size of the memory block (remembering its capacity and actual filling) - the number of memory allocations / releases drops to O(1) per element ...

And yet - you do not have a copy constructor and an assignment operator, so with these operations, the generated ones will perform a shallow copy, and you will have a problem with double freeing the memory. This is very unpleasant, so you have to either write your own, or ban them altogether!