On line 40 when I delete the array used as a parameter in the function, my understanding is when I call the function and use myArr, another pointer is created. After that it is not used in the function from what I can tell.
So what was the point in creating it in the first place? |
Yes, another pointer is created. This pointer points to the same memory of the argument in the function call.
It is used only to
delete[]
the memory pointed by it, and since the original also points to that memory it's like calling
delete[]
on that.
On line 41 you then set the copy to null (see below), but this is actually unnecessary because the copy isn't used again in the function and the original pointer is still pointing to the old (now invalid) memory.
Couldn't I had just created the function and make it use just the size parameter? |
Yes, but in that case you'd have to
delete[]
the pointer before calling the function. Otherwise the old memory becomes unreachable, therefore undeletable.
In your case it's not necessary because myArr doesn't point to any allocated memory.
Also when the copy is made does it point to a different memory location that has the same value as the one myArr points to or does it point to the same memory location, which would mean I would have 2 pointers going to the same place? |
It points to the same memory location. Like I said, this is done to allow the function to free the memory pointed by the original array (doing so using the copy, that points to the same memory). It goes without saying that the pointer argument is also supposed to be assigned to the return value of the function, otherwise it keeps pointing to the deleted memory.
Also on line 17 when = 0 is used I'm assuming that means the pointer isn't pointing to any memory at that moment. Is that correct?
|
That assignment does exactly what you read: it assigns the pointer to the 0th memory address.
In most, if not all, code you'll ever see it's the only case where a memory address is explicitly used. Usually you assign using other pointers or to the return value of a
new
statement.
The 0th address, also called null (Null, NULL, nil, nullptr in C++11) is special because it is always invalid. No memory will ever be allocated starting from 0, so assigning a pointer to null means that that pointer is not pointing to anything.
Being invalid, trying to access it will result in an error (segmentation fault, segfault).
Pointers should never point to deallocated memory. So after you delete them, either assign them to new memory or set them to null to signal they are not pointing to anything (unless you are SURE you will not use them again EVER).
Deleting a pointer to invalid memory usually causes an error, unless it points to null, in which case it just does nothing.