Kawson
Kawson

Reputation: 136

C++ Why there is error when I delete pointer?

I have problem with visual studio ( i think so ). When i try compile it in Visual Studio i'm getting error (breakpoint).

int main()
{
    int p = 4;
    int d = 7;
    int* x = &d;
    cout << *x << endl;
    delete x;
}

I'm gettin error like this. ERROR Am i doing something wrong??? In code blocks it works. When i restart visual studio im getting this error: https://i.sstatic.net/JWrRy.png

Upvotes: 0

Views: 1968

Answers (2)

fabian
fabian

Reputation: 82491

delete pointer; does not delete the pointer itself, but the data that the pointer is pointing to. In this case, that happens to be memory that's allocated on the stack when the scope of the main() function is entered, and is freed automatically when the scope of main() exits. Your program attempts to free this memory using delete, which is undefined behavior since you're calling delete for memory that wasn't allocated using new.

In your case, you should simply remove the delete. All memory on the stack is freed automatically at the end of main(): p, d and x (the variable holding the address, not the address it points to) were all allocated on the stack.

Upvotes: 5

Mithrandir
Mithrandir

Reputation: 25397

You are pointing to an integer value on the stack. You can only delete dynamically allocated memory on the heap. You can delete it if it was created by calling new or malloc().

int* ptr1 = new int;  
int* ptr2 = new int(20); 
int  intval = 20;

delete ptr1; // OK, free memory on heap
delete ptr2; // OK, free memory on heap
delete intval; // Error 

Upvotes: 1

Related Questions