Delete a pointer after the arithmetics

后端 未结 5 2030
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 06:28
int main() {
  int* i = new int(1);
  i++;
  *i=1;
  delete i;
}

Here is my logic:

I increment I by 1, and then assign a value to it. Then

5条回答
  •  执笔经年
    2020-12-12 06:59

    In this case you need to have a short understanding how the heap memory management works. in particular implementation of it, when you allocate an object you receive a pointer to the start of the memory available to you to work with. However, the 'really' allocated memory starts a bit 'earlier'. This means the allocated block is a bit more than you have requested to allocate. The start of the block is the address you have received minus some offset. Thus, when you pass the incremented pointer to the delete it tries to find the internal information at the left side of it. And because your address is now incremented this search fails what results in a crash. That's in short.

提交回复
热议问题