-
Copying character arrays
I'm trying to make a simple binary search tree. Each node has a char data type, and a pointer to a char. For the tree class, this information needs to be filled in when inserting items. I am having troubles inserting the character array. Here is my class. I am trying to keep this simple, no complications needed.
Code:
#include <cstring>
class bNode
{
private:
char ch;
char *code;
bNode *left, *right;
public:
bNode() { ch = 0; }
~bNode() { delete code; }
char getCh() { return ch; }
char* getCode() { return code; }
void setCh(char c) { ch = c; }
void setCode(char *c)
{
code = new char[strlen(c)+1];
strcpy(code, c);
}
};
The program just crashes, and I've searched and found that the crash occurs on the call to setCode() for a node. Anyone know what I am doing wrong?
-
Well you are going to want to first delete the memory in which you first allocated to code so i would delete [] code. But other than that I don't see why it is failing. What are you passing to it?
Also i would set code to 0 when constucting your node.
Not a huge deal also I would make
Code:
char* getCode() { return code; }
Code:
char* getCode() const { return code; }
-
inserting arrays wont wont work if you use ordinary delete.
you must use delete [].
you might need to set a flag wheter what youve inserted is an array or not and call the corresponding delete function in the destructor.
-
Here let me re post what I meant.
Code:
void setCode(const char *c)//Make this const
{
delete [] code;//each time you were reassigning this you were creating a memory leak without delete
code = new char[strlen(c)+1];
strcpy(code, c);
}
Also in your constructor I would do this
Code:
bNode()
{
char = 0;
code = 0;
}
And in the destuctor
Code:
~bNode()
{
delete [] code;
}
I would also make your return c and code functions const.
Code:
char getCh() const { return ch; }
char* getCode() const { return code; }
One more thing :)
Code:
void setCh(const char c) { ch = c; }
//make this parameter const as well
-
Thank you, I've found the problem, it was because I needed delete at the beginning of the function (along with the extra []). I did take in to mind adding consts where needed, which I've started doing. Thanks again, now I just have to fix the other problems.