Consider the portion of code below (please do not care about deleting the firstArray
and secondArray
):
int *firstArray = new int[10];
int *secondArray = new int[20];
firstArray = secondArray;
I have three questions here:
Is the expression firstArray = secondArray;
safe even though they have two different sizes?
ps: It seems the compiler (code::blocks) does not complain.
Now that firstArray
and secondArray
have the same address, what happens if I delete one of the arrays, is the other one deleted too?
Why, when I delete the second one, the application crashes.
Okay, let's talk about what you're doing here.
Imagine that firstArray holds the memory address 0x1000 and secondArray holds address 0x2000. After this assignment, they both hold 0x1000, and 0x2000 is orphaned.
If you delete [] firstArray, then continuing to reference 0x1000 by either pointer can lead you into trouble. You're going to step all over who knows what.
You've now engaged in undefined behavior, and crashes are common when you engage in undefined behavior.
Now, here's some opinion. It's important to understand the underlying memory systems, but once you do, start using various smarter containers. You can use std::array instead, for instance, and then you don't have to deal with memory allocation at all. This eliminates huge classes of bugs.