about delete char** p = new char*[5]

If at last I delete p only, positions to which 5 pointer_to_chars points lost a name to access, is it a memory leak case? How to solve such thing?
and each ptr_to_char points a string constant like *p[2] = "mon";

1
2
3
4
5
char** p = new char*[5];
char*[0]="sun";
char*[1]="mon";
...
delete p;
when ever you use new [] you should use delete []

What you are doing is deleting only the first element in the array not all the elements.

1) If you use new[] (with brackets), you must use delete[] (also with brackets).

2) literals should be const char*, not char*

3) char*[0]="sun"; <- this is nonsense. You probably meant this:
p[0] = "sun";

4) If you did not use new to allocate space, then you do not need to delete. Here, since you only did new[] for p.. you only need to delete[] p. You did not do new[] to allocate space for p[0], so you do not need to (and must not) delete[] p[0].

This code is perfectly acceptable:
1
2
3
4
5
const char** p = new const char*[5];
p[0] = "sun";
p[1] = "mon";
//...
delete[] p; // <- no memory leak 



5) You shouldn't use new unless you have to. This is even more true for new[]. I strongly recommend you use container classes like std::vector and std::string, rather than using new.

This code is less error prone and less dangerous:
1
2
3
4
5
6
7
std::vector< std::string > p;
p.resize(5);
p[0] = "sun";
p[1] = "mon";

// no need to delete anything ... it's all done automatically
//  no risk of memory leaks. 
@Disch,

but after delete [] p; the way to record each string constants' address is deallocated, would that be a problem? I mean there is no way to access those 5 strings, but they still there. Or they would be automatically released?
But you didn't allocate the memory for those string constants yourself, so you have nothing to worry about.

You only delete or delete[] what you allocated yourself with new or new[].
OIC thanks a lot, guys!
Topic archived. No new replies allowed.