C++ conversion of string to char * which is then returned

i'm doing some work in c++ and came across this piece of code:

char* intToChar(RandomObject o) {
   string integerStr = to_string(o.toNumber());
   char * integerChar = new char[integerStr.size()+1];
   copy(integerStr.begin(), integerStr.end(), integerChar);
   integerChar[integerStr.size()] = '\0';
   return integerChar;
}

integerChar is returned and assigned like this:

struct Field {
   char *name;
   char *value;
};

std::vector<Field> rowData;

Field field;
field.name = i->key;
field.value = intToChar(i->value);
rowData.push_back(field);

but i don't see anywhere he would free integerChar or the field object ... is this bad? will this create a memory leak?

Answers


Short answer: probably yes. intToChar allocates memory, which is then assigned to field.value. If there is no delete[] called for field.value (directly or indireclty), the memory is leaked.


Well, I see the code uses both string (is it std::string) and char* which is bizarre to me. Stick with string and avoid dealing with memory allocation and release.

string intToChar(int o) 
{
   return to_string(o.toNumber());
}

struct Field {
   std::string name;
   std::string value;
};

Field field;
field.name = i->key;
field.value = intToChar(i->value);
rowData.push_back(field);

Every use of new must be matched with a use of delete. Or in this case, delete[]. So, yes, if the delete[] is missing, memory is leaked.


You don't have to free the field object (it was created on the stack in this case, so it will normally be discarded when the corresponding thread ends) but the memory for integerChar, allocated with new, has to be deallocated somewhere.


Need Your Help

Is possible to bind to express callback promise?

node.js express promise

Is possible to bind to express callback promise ?