deleting equal pointers

So I'm passing a char pointer to a function which creates a char array, returning to main() and setting another char pointer equal to the first one. My question concerns the deleting of these; if I try to delete both I get in trouble but deleting either of them seems to work. However I don't want to make a mess of the memory and wonder what's the right procedure? Below is the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void func(char *&c) {
	
	c=new char[3];
	c[0]='f';
	c[1]='r';
	c[2]=0;
}

int main() {

	char *c1, *c2;
	func(c1);
	c2=c1;
	
	cout << c1 << "   " << c2 << endl;
	
	delete [] c1;
	//delete [] c2;
	
	return 0;
}
delete([]) does not delete a pointer; it deletes the allocated heap memory it points to. Regardless of how many pointers are pointing to it, the memory is only there once, does only has to be deleted once. In short: every new statement require exactly one delete statement.

A good way to handle dynamic memory:
Every time you type "new", immediately type the "delete" statement that goes with it and put a few blank lines between them, where the rest of your code will come. That way, you don't have to think of memory management while doing the actual work.
Oh I see, that makes sense. Thanks!
closed account (1vRz3TCk)
jorgen,

'plain' pointers can be dangerous to use. In your example you have two pointers pointing to the same object in memory. When this object is deleted via one of the pointers the other knows nothing of this and that can lead to undefined behavior if it is used. It would be best to read around the various types of 'smart' pointers that are available.
Last edited on
Topic archived. No new replies allowed.