Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my program crash when I increment a pointer and then delete it?

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.

like image 590
Beetroot Avatar asked Dec 16 '16 12:12

Beetroot


People also ask

What happens when you delete pointer C++?

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.

Should you always delete a pointer?

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.

What happens when you increment a pointer C++?

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.

Do you have to delete every pointer C++?

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 .


1 Answers

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.

like image 189
Bathsheba Avatar answered Sep 19 '22 13:09

Bathsheba