0

I have a problem when using 'delete' operator. It is identified as a syntax error by VS2013 with Nov 2013 CTP compiler, giving the message: "expected a declaration". Here is the code:

int a = 1;
int* p = &a;

int* snj = new int[10];

delete p;
delete[] snj;
user3650284
  • 137
  • 1
  • 3
  • 10

3 Answers3

4

C++ doesn't let you write arbitrary expressions in the top-level like Python or other languages. You need to place your code in a function, probably main in this case:

int main()
{
    int a = 1;
    int* p = &a;

    int* snj = new int[10];

    delete p;
    delete[] snj;
}

Note that using delete on a pointer which wasn't allocated using new is undefined behaviour.

Things like this are very basic and should be covered by your introductory book. If you don't have an introductory book, you should get one.

Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

p points to the address of a. a is a local variable decalred on the stack. You can only call delete on dynalically allocated heap memory (Any variable created using the new keyword).

a is deleted automatically when it goes out of scope.

hello_world
  • 442
  • 3
  • 7
0

You should not delete p since it is not pointing to a heap element, it points to a stack element.

AndersK
  • 35,813
  • 6
  • 60
  • 86