I was solving some programming exercise when I realised that I have a big misunderstanding about pointers. Please could someone explain the reason that this code causes a crash in C++.
#include <iostream> int main() { int* someInts = new int[5]; someInts[0] = 1; someInts[1] = 1; std::cout << *someInts; someInts++; //This line causes program to crash delete[] someInts; return 0; }
P.S I am aware that there is no reason to use "new" here, I am just making the example as small as possible.
delete keyword in C++ Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.
Also when you access freed memory you can't guarantee that the data that is returned to you is the data you wanted/expected, so you should only do delete pointers in the destructor of their owner or when you are sure that you won't need them anymore.
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
You don't need to delete it, and, moreover, you shouldn't delete it. If earth is an automatic object, it will be freed automatically. So by manually deleting a pointer to it, you go into undefined behavior. Only delete what you allocate with new .
It's actually the statement after the one you mark as causing the program to crash that causes the program to crash!
You must pass the same pointer to delete[]
as you get back from new[]
.
Otherwise the behaviour of the program is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With