Hi all,
If I want to check if memory has already been alocated to a pointer, and if it has I wnat ot delete it, is this how it would work?
theGraph = new MyObject[size()];
if (theGraph != 0){ // or even NULL
delete[] theGraph;
}

This seems intuitive to me, however whether memory has been allocated or not, it still tries to delete. E.g. if the memory address pointed to by the pointer is 0xcdcdcdcd it doesn't take this as NULL even though its not the result of a memory allocation!
Not sure if this makes sense, but if anyone can spot my problem I'd be grateful!
Cheers

There are many syntatical ways of accomplishing this task, for instance:

#define SIZE 5

int main() {
	int *n;
	n = new int[SIZE];

	if (n) // if n does exist
		delete[] n;
	// [b]or[/b]
	if (n != NULL) // if n isn't un-initialized [double negative]
		delete[] n;

	return 0;
}

Both checking if "n" and/or "n does not equal NULL" means the same thing. Since an if simply tests the numeric value of an expression, certain coding shortcuts are possible like the first one showed above.


P.S. Working with 2 dimensional arrays do undertake further steps to free memory than just calling "delete[]" once.


Hope this helps,
- Stack Overflow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.