Such code will cause the program to crash. If you remove the "delete" in the function, it will work fine. In principle, it is clear that "delete" frees the dynamic memory, and I created this pointer not during the allocation of dynamic memory, but during the transfer of one of the array elements to the function. But I absolutely do not know the details of this. Could someone kindly poke into the article or explain to the teapot what the problem is in detail, because of which the "delete" and the program hang?

int foo(int* ab) { delete ab; return 0; } int main() { int **arr = new int* [5]; for (int i = 0; i< 5; i++) { arr[i] = new int [6]; for (int j = 0; j < 6; j++) { arr[i][j] = rand() % 5; } } foo(&arr[1][1]); cout << "DEATH!" << endl; return 0; } 
  • one
    Only those pointers that were created via new / new [] respectively can be deleted via delete / delete [] . You can do delete [] arr[1] or delete [] &arr[1][0] , because this is the same pointer that was returned by the operator new [] , but you cannot make delete &arr[1][1] , indefinite behavior if I remember correctly // UPD: well, yes, arrays need to be deleted through delete [] , as I was reminded below - andreymal

1 answer 1

  1. you are trying to allocate and free memory manually
  2. you are trying to free memory using a pointer that was not received during memory allocation
  3. You are trying to free up memory using a method that does not match the method that was used to allocate memory.
  4. the number of memory free does not match the number of memory allocations
  • 3. Why not appropriate? It seems here on the whole code only new / delete, not? // 4. For a simple learning example, this is not very important, the OS itself will clean up all the leaks :) - andreymal
  • @andreymal delete [] - extrn
  • @extrn, I realized, I overlooked - andreymal
  • @andreymal There are no new [] calls at all; there are only new [] calls that must be matched by delete [] , not delete . 4) memory leaks on exit - always an error - VTT
  • @VTT 4) Is this your personal opinion or is it written somewhere in the specification? - andreymal