-
Pointer problem
Hi, I want to understand why I get a runtime error with these lines: I try to delete a pointer that was never allocated somewhere (don't ask me why...) but I get an error telling me that the pointer is used without being defined...
Code:
int *a;
delete a;
a = new int;
But then is there a way to check if a pointer allocated with NEW points somewhere or not?
I tried using this, but still it says that the variable is used without being defined...
Code:
if (a != NULL) delete a;
-
a is not initialized, so it points to some unknown location. You cannot call delete with some unknown location that wasn't allocated with new. If you initialize your variable (always a good idea) to 0 or NULL, then it will work (i.e. the delete will not fail).
There is no way to tell if a pointer points at "delete-able" memory or not other than to make sure your code uses the correct logic to remember that detail. One way is to always set pointers to null if they are not being used.
This is why C++ has many tools available so that you don't have to manage dynamic memory yourself.
-
Will make sure your pointer is properly initialized when declared inside a function.
-
Thanks, it worked!
But what about "int()", is this some sort of constructor? In what way it makes sure it is initialized properly?
-
It works like a constructor. The parentheses just mean to value-initialize the data stored in the location you just allocated space for. In the case of an int, it means initialize it to 0. You could put any integer into the parentheses and your new int would be initialized to that number.
-
> but I get an error telling me that the pointer is used without being defined...
Because it appears "on the right" before it appears "on the left" (of an assignment)
The compiler is smart enough to know that you never assigned a value to it, so it warns you that you're using it before you define it.
Simple innit?