Error part of code
Myarray::Myarray(const Myarray& p) {cout << "copy" << endl; this->mSize = p.mSize; this->mCapacity = p.mCapacity; this->array = new int[p.mCapacity]; //new allocates too little space !!!! For (int I = 0; i < p.mSize; ++i) { this->array[i] = p.array[i]; } } Myarray::~Myarray() { if (array ! = NULL) {STD ::cout << "destructor" << STD ::endl; delete[] this->array; this->array = NULL; }}Copy the code
Summary of information search:
Question:
1. Memory out of bounds :(own problems) too little space for new, out of range when used, change the value on the address that does not belong to the program.
2. A shallow copy problem occurs. The same address is deleted repeatedly
int* p1 = new int(50); int* p2 = p1; //p2 and p1 now refer to the same memory address cout << *p1 << endl; cout << *p2 << endl; delete p1; //OK delete p2; // the memory referred to by p2 has been freed by delete p1, and cannot be deleted againCopy the code
3. The memory released by the system is deleted
int* a = new int[10];
int b[50];
a= b;
delete [] a;
Copy the code
Delete new int[10]; B [50] allocates space on the stack. There are two results: 1. The original space is not freed. 2. Forcibly release b released by the system [50].
4. First group address change: deleting dynamically allocated Pointers does not point to the original address
int *a = new int[10]; *a= 1; *a++ = 2; delete[] a; / / errorCopy the code
++ now changes the address to which the pointer points; Make sure the pointer points to the original position before releasing. The first element is not released, and one more element is deleted at the end
- Different scope, delete under different operation.
Attention!!!!!
After delete pointer, set pointer to NULL. Such as:
delete p;
p = NULL;
Copy the code