Pointer and new fail

Let's start with what I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
void SwapArray(int* arr)
{
  int* newArr = new int[10];
  int* temp = arr;
  arr = newArr;
  delete[] temp;
}
int main()
{
  int* A1 = new int[5];
  SwapArray(A1);
  delete[] A1;
}

This gives me a 'Debug Assertion Failed' _BLOCK_TYPE_IS_VALID(pHead->nBlockUse).
I don't get it what i've done wrong and what puzzles me is if I remove the function and execute what the function does in the main, it doesn't crash. Can anybody figure out what i've done wrong?
The pointer of A1 doesn't change (like you expected). So you delete the memory of A1 twice

You need a reference or a pointer to the pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
void SwapArray(int** arr)
{
  int* newArr = new int[10];
  int* temp = (*arr);
  (*arr) = newArr;
  delete[] temp;
}
int main()
{
  int* A1 = new int[5];
  SwapArray(&A1);
  delete[] A1;
}
THX!^^
closed account (zb0S216C)
temp is an issue. When temp was declared, it was initialized by its assignment to the region which arr was pointing to. Then, when you deleted temp just before exiting the function, you deleted the region that arr was pointing to. In addition, when A1 was deleted, the memory that temp released was the region that A1 was pointing. In effect, A1 deleted memory that was no longer there.

Wazzak
Topic archived. No new replies allowed.