Delete a pointer after the arithmetics

后端 未结 5 2037
伪装坚强ぢ
伪装坚强ぢ 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:04

    Let's take it step by step:

    int* i = new int(1);  // 1. Allocate a memory.
    i++;                  // 2. Increment a pointer. The pointer now points to
                          //    another location.
    *i=1;                 // 3. Dereference a pointer which points to unknown
                          //    memory. This could cause segmentation fault.
    delete i;             // 4. Delete the unknown memory which is undefined 
                          //    behavior.
    

    In short: If you don't own a piece of memory you can't do arithmetic with it neither delete it!

提交回复
热议问题