Please help memory management
-
void CreateFolderPath(string Path) { char *strFolderPath = new char[Path.size() + 1]; strcpy_s(strFolderPath, Path.size() + 1, Path.c_str()); _mkdir(strFolderPath); } string ConvertIntToString(int cipher, int objintiger) { string temp; char *Res = new char[cipher]; sprintf_s(Res, cipher, "%02d", objintiger); temp = Res; return temp; } // Is there room for memory problems?
-
void CreateFolderPath(string Path) { char *strFolderPath = new char[Path.size() + 1]; strcpy_s(strFolderPath, Path.size() + 1, Path.c_str()); _mkdir(strFolderPath); } string ConvertIntToString(int cipher, int objintiger) { string temp; char *Res = new char[cipher]; sprintf_s(Res, cipher, "%02d", objintiger); temp = Res; return temp; } // Is there room for memory problems?
There are problems (memory leaks). You must
delete
memory allocated withnew
when not used anymore:void CreateFolderPath(string Path)
{
char *strFolderPath = new char[Path.size() + 1];
strcpy_s(strFolderPath, Path.size() + 1, Path.c_str());
_mkdir(strFolderPath);
delete [] strFolderPath;
}string ConvertIntToString(int cipher, int objintiger)
{
string temp;
char *Res = new char[cipher];
sprintf_s(Res, cipher, "%02d", objintiger);
temp = Res;
delete [] Res;
return temp;
}For your first example there is even no need to copy the string. Just pass it to
_mkdir()
:void CreateFolderPath(string Path)
{
_mkdir(Path.c_str());
} -
There are problems (memory leaks). You must
delete
memory allocated withnew
when not used anymore:void CreateFolderPath(string Path)
{
char *strFolderPath = new char[Path.size() + 1];
strcpy_s(strFolderPath, Path.size() + 1, Path.c_str());
_mkdir(strFolderPath);
delete [] strFolderPath;
}string ConvertIntToString(int cipher, int objintiger)
{
string temp;
char *Res = new char[cipher];
sprintf_s(Res, cipher, "%02d", objintiger);
temp = Res;
delete [] Res;
return temp;
}For your first example there is even no need to copy the string. Just pass it to
_mkdir()
:void CreateFolderPath(string Path)
{
_mkdir(Path.c_str());
}Thank you very much!!!! :)