Dynamic Array Template Class Trouble

I created a dynamic array class named chamber and recently edited it to handle all types with a template. The odd thing is, that it only doesn't work with strings. There is really nothing that does work with strings, but I have not been able to pinpoint what it is. Here is my code (on codepad due to it's length): http://codepad.org/4qQHdHQF

If anyone can provide some insight on my problem that would really great.
Lets start right at the beginning:
This constructor and destructor can cause segentation faults.
1
2
3
4
5
class chamber
{
    public:
        chamber(){itsLength = 0; pChamber = new T[itsLength]; tempChamber = new T;} //Constructor sets length and creates a chamber
        ~chamber(){delete pChamber; delete tempChamber;} //deletes pointers 



tempChamber = new T; shouldn't be on there (I guess I uploaded a slightly order version). Is it a segmentation fault because I am deleting tempChamber? If so, why does it work with all types but strings?
1. In the constructor
with itsLength =0 then pChamber = new T[itsLength] will return a bad ponter, because you
are asking for zero size array.

2. In the destructor
delete pChamber; should be delete [] pChamber;


Coming back to why you have a problem with string but not say for example with int
Consider the following:
(for these examples we will make the pChamber pointer public)

1
2
3
4
5
6
7
int main ()
{
      chamber<int > cs;  // cs will have a rubbish pChamber pointer as we said earlier

       cout << cs.pChamber[0] << endl; 
      return 0;
} 


The above will work because even if pChamber is a useless pointer really, all an integer is is 4 bytes - nothing special at all.


But:
1
2
3
4
5
6
7
int main ()
{
      chamber<string > cs;  // cs will have a rubbish pChamber pointer as we said earlier

       cout << cs.pChamber[0] << endl;  //crash
      return 0;
} 


This fails because a string is more complex than a simple int - it is a class - with a pointer member.
So you have a rubbish pointer (pChamber), pointing to unitialized data, which you are trying to
decode as a valid string variable, which it most certainly is not - which means that the pointer member of an invalid string will be itself invalid - hence the problem.

1. In the constructor
with itsLength =0 then pChamber = new T[itsLength] will return a bad ponter, because you
are asking for zero size array.


Ah, thanks. I switched it to this:

chamber(){itsLength = 0; pChamber = new T[1]; tempChamber = new T[1];}

2. In the destructor
delete pChamber; should be delete [] pChamber;


I didn't know there was a difference, thanks.
Topic archived. No new replies allowed.