Why doesn't C++ give compiler error when you call delete on a non-pointer stack allocated variable? [closed]-Collection of common programming errors
If you are thinking of something like this:
int a;
int *pa = &a;
delete pa;
Then you won’t get a compiler error because the above code, while wrong, is not illegal by language definition. However, the compiler may issue a warning if the case is obvious enough (I didn’t try, but I guess it won’t). A static analyzer tool should detect this though.
If you have something like this, though, there is no way the compiler would know that something is wrong:
void foo(int* pa)
{
delete pa;
}
...
int a;
foo(&a);
To detect this, you’ll definitely need a good static analyzer such as Coverity. But generally you should avoid patterns like this. Deleting a pointer should always be the responsibility of the class (or other entity) that created it. Even better, you should use smart pointers instead of calling new/delete manually (you’ll need a C++11 compatible compiler or use Boost).