Why I can not delete another element from the array with a pointer

Consider the following code:

int main()
{
  int *intArPtr = new int[100];
  int *intArPtr1 = intArPtr + 1;

  delete [] intArPtr; //ok
  //delete intArPtr; //valgrind warning, but no leaks!
  //delete intArPtr1; //invalid pointer error

  return 0;
}

I know what delete [] intArPtris the only valid way to delete this array, but I'm just wondering:

  • Why delete intArPtrdoes not it give memory leaks? It is undefined, and I was just lucky that I do not?
  • Why delete intArPtr1gives a runtime error? Why doesn't it delete all elements, but first from the array?
  • How does the C ++ runtime know the size of the allocated array (to delete [])? Is it stored somewhere?
+4
source share
3 answers
  • delete intArPtr ? undefined, , ?

, undefined delete , new[]. -, .

, , , , delete delete[] . , , : delete delete[] - . (. № 3 ).

  1. delete intArPtr1 ? , ?

delete , new. . new, . .

  1. ++ ( [])? - ?

, , . delete , , 4 8 . - , .

++ , , . , -. .

:

+12
  • intArPtr ? undefined, , ?

. delete delete[] , . . delete, .

  1. intArPtr1 ? , ?

intArPtr1 . delete, .

  1. ++ ( [])? - ?

.

0

:

  • In your example, there are no memory leaks. In fact, deleting an array without [] will only lead to memory leaks if the objects inside the arrays have allocated memory and should free this memory in the destructor. In all other cases, improper deletion will not lead to a memory leak.
  • Since the size of the allocated memory is stored immediately before the pointer. When you refer to some other element of the array, but the first, there is no proper memory size.
  • See 2.
-2
source

Source: https://habr.com/ru/post/1609710/


All Articles