How to check if memory is alocated to a pointer?

Hi friends,

I have a global pointer variable that can be called depending on conditions and not to reallocate the variable, i am using the method like, for x for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int size;
double *x = NULL;

do some stuff



if(x == NULL)
x = new double[size];




do some stuff



delete []x;






is this the right way to proceed?



Abu
Last edited on
Yes, but you should also check for NULL before deleting. If it's not pointing anywhere, delete can lead to problems. Also, the official "NULL" for pointers is the "nullptr" keyword. It's the exact same as "p = NULL" or "p = 0", but a bit more obvious.
closed account (zb0S216C)
Gaminic wrote:
"you should also check for NULL before deleting."
-1 "delete" is guaranteed to do nothing with a null-pointer.

Standard wrote:
3.7.3.2 Deallocation functions, Paragraph 3: "The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect."
Wazzak
Last edited on
Thanks!
I stand corrected!
Try to use a debugger. For Linux - is valgrind, for windows - deleaker, or memchek, or vld. They will show where undeleted object and need to clear memory!
Last edited on
Topic archived. No new replies allowed.