I have to store lots of program-generated integers as xml, for example like this: <tag>1234</tag>... I've been using the following code till now:
TiXmlDocument doc(filename);
TiXmlNode *node;
int number;
char *temp;
...
while () {
number = giveMeANumber();
temp = new char[5];
sprintf(temp,"%d\0",number);
node = new TiXmlText(temp);
doc.InsertEndChild(*node);
}
doc.SaveFile();
...
However, i soon realized that this way i lose control of the 'temp' values, causing memory leaks, since TiXmlText doesn't do anything with its 'value' member when destructed. On the other hand, neither can i skip the repeated allocations of 'temp', since TiXmlText's constructor (namely the SetValue() member) assigns 'value' the given pointer and does not copy the character array it points to.
Any ideas?
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
I have to store lots of program-generated integers as xml, for example like this: <tag>1234</tag>... I've been using the following code till now:
TiXmlDocument doc(filename);
TiXmlNode *node;
int number;
char *temp;
...
while () {
number = giveMeANumber();
temp = new char[5];
sprintf(temp,"%d\0",number);
node = new TiXmlText(temp);
doc.InsertEndChild(*node);
}
doc.SaveFile();
...
However, i soon realized that this way i lose control of the 'temp' values, causing memory leaks, since TiXmlText doesn't do anything with its 'value' member when destructed. On the other hand, neither can i skip the repeated allocations of 'temp', since TiXmlText's constructor (namely the SetValue() member) assigns 'value' the given pointer and does not copy the character array it points to.
Any ideas?
Actually, it does copy the characters it points to:
The constructor calls:
void SetValue(const char * _value) { value = _value;}
Which uses the rather deceptive C++ trick of a copy constructor, which is what threw you off I suspect. But value is a string:
TIXML_STRING value;
so it's a copy.
So following the Text node creation,
delete [] temp
should be fine.
lee