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; }
new
/new []
respectively can be deleted viadelete
/delete []
. You can dodelete [] arr[1]
ordelete [] &arr[1][0]
, because this is the same pointer that was returned by the operatornew []
, but you cannot makedelete &arr[1][1]
, indefinite behavior if I remember correctly // UPD: well, yes, arrays need to be deleted throughdelete []
, as I was reminded below - andreymal