Delete a pointer after the arithmetics

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

    What your program shows is several cases of undefined behaviour:

    1. You write to memory that hasn't been allocated (*i = 1)
    2. You free something that you didn't allocate, effectively delete i + 1.

    You MUST call delete on exactly the same pointer-value that you got back from new - nothing else. Assuming the rest of your code was valid, it would be fine to do int *j = i; after int *i = new int(1);, and then delete j;. [For example int *i = new int[2]; would then make your i++; *i=1; valid code]

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 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)++;
    
    0 讨论(0)
  • 2020-12-12 07:10

    Who allocates is who deallocates. So you should not be able to delete something you did not new by yourself. Furthermore, i++;*i=1; is UB since you may access a restricted memory area or read-only memory...

    The code made no sense . I think You have XY problem. If you could post your original problem there will be more chance to help you.

    0 讨论(0)
提交回复
热议问题