Segfault when deleting pointer

后端 未结 5 1529
南笙
南笙 2021-01-03 12:32

I\'ve been experiencing segfaults when running some C++ code. I\'ve isolated the problem to a line in the program that deletes a pointer. Here\'s a simple example that pro

5条回答
  •  庸人自扰
    2021-01-03 13:23

    When you allocate a variabile with new:

    int *a=new int(4);
    

    This variable is put on the heap, which contains all the memory dnamicly allocated. If instead you declare a variable:

    int a=4;
    

    a is allocated in the stack, where there is static memory. Dynamic memory can be deallocated with delete from the user, but static memory can not. Static memory is automaticlly deallocated when yuo exit froma function:

    void function()
    {
        int a;
    }
    

    When the function ends a is automatically deallocated (except for variables declared with the keyword "static"). Also variables in main function are automatically deallocated. So you can not say to the program to deallocate a variable in the stack. In your example number is on the stack, pointer points to number which is in the stack, if you delete it you are trying to delete a variable in the stack, which is not allowed,because it's not dynamic memory.

提交回复
热议问题