Program crashes when deleting a pointer pointing to the heap?

后端 未结 2 371
盖世英雄少女心
盖世英雄少女心 2020-12-22 13:29

If I go...

int *foo = new int;  
foo += 1; 
delete foo;    

Most of the time it crashes. Is there a reason for this? I\'m trying to have t

相关标签:
2条回答
  • 2020-12-22 14:10

    You must pass to delete the value that new returned. You don't do that.

    I think that you are confused as to what you are passing to delete. I think that you believe that delete foo will delete the memory associated with the variable. It doesn't. It deletes the memory whose address is stored in foo.

    As an example, this is legitimate:

    int* foo = new int;
    int* bar = foo;
    delete bar;
    

    What matters is not the name of the variable, but rather the value of the variable.

    Here's another example:

    int* arr = new int[10];
    int* ptr = arr;
    for (int i; i < 10; i++)
    {
        *ptr = i;
        ptr++;
    }
    delete[] arr;
    

    In order to perform pointer arithmetic, and retain the address returned by new[], we introduced an extra variable. I used an array because it doesn't make sense to perform arithmetic on a pointer to a single value.

    Note that in the code above, it could be written more clearly using arr[i] = i and so avoid the need for a second pointer variable. I wrote it as above to illustrate how you might code when pointer arithmetic is the right option.

    0 讨论(0)
  • 2020-12-22 14:33

    The only thing you can safely pass to delete is something you got when you called new, or nullptr, in that case the delete won't do anything.

    You changed the value of the pointer - therefore it isn't "something you got when you called new"

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