Delete a pointer after the arithmetics

后端 未结 5 2028
伪装坚强ぢ
伪装坚强ぢ 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 07:08

    The problem lies here:

        i++;
    

    This line doesn't increment the value i points to, but the pointer itself by the number of bytes an int has (4 on 32-bit platform). You meant to do this:

        (*i)++;
    

提交回复
热议问题