简体   繁体   中英

Why increment a pointer casuing crash?

i was learning about allocating and releasing memroy in c++ programming.i tried to increment my pointer and then use delete afterward. it crashed ! why is that happening ?

int *pint = new int ;
double *pDouble = new double;

*pint = 3;
*pDouble = 3.5; 

pint++;
pDouble++;

delete pint;
delete pDouble;

Problem

int *pint = new int ;

Dynamically allocates a single int . Later,

pint++;

Increments the pointer, not the value. Incrementing a pointer advances the pointer one element, so pint++ advances the address in pint by one int to point out of bounds of what was allocated. Attempting to access or delete what is pointed at will invoke Undefined Behaviour and will most likely cause the program to crash.

pDouble++;

has a the same effect, but advances to the next double .

Solution

There isn't much of a solution other than don't do this. If you need to increment a pointer, to iterate through an array for example, make sure you keep a pointer to the original address so that you can release it when you are finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM