After some 'digging' into the dark corners of legacy code I've found class, which handles INI files. It does reading and writing to the file, but I haven't found any exception handling logic. What kind of potential problems, if any, can you detect and what is your suggestion/advise for improving the code, based on these three C++ code snippets:
Constructor
IniValue::IniValue(const char* FileName, const char* Section, const char* Entry, int sz, PersistMediumEnum medium_, int iniprofileId_)
:filename(NULL)
,section(new char[strlen(Section)+1])
,entry(new char[strlen(Entry)+1])
,buffer(new char[sz])
,bufsiz(sz)
{
if (FileName == NULL) {
FileName = "somefile.ini";
}
// 'GetFullInifileName' calls windows functions 'GetEnvironmentVariable', 'CreateDirectory', 'CopyFile', 'DeleteFile'
std::string fullname = GetFullInifileName(FileName);
filename = new char[fullname.length()+1]; strcpy(filename, fullname.c_str());
strcpy(section, Section);
strcpy(entry, Entry);
buffer[0] = 0;
}
Some function, which reads values from the file:
void IniValue::TheGetProfileString() {
char* defstr = new char[bufsiz];
strncpy(defstr, buffer, bufsiz);
IniPersistIF* inf = IniPersistIF::get(medium);
//calls windows 'GetPrivateProfileString'
inf->Read(section, entry, defstr, buffer, bufsiz, filename, iniprofileId);
delete [] defstr;
}
Destructor
IniValue::~IniValue() {
IniValue* thys = this;
assert(section[0] != '\0');
assert(filename[0] != '\0');
IniPersistIF* inf = IniPersistIF::get(medium);
assert(inf != NULL);
assert(section[0] != '\0');
assert(filename[0] != '\0');
// Calls Windows 'WritePrivateProfileString' function
inf->Write(section, entry, buffer, filename, iniprofileId, defaultval, bModified);
delete [] buffer;
delete [] entry;
delete [] section;
delete [] filename;
}
defaultval
, but the destructor frees it. \$\endgroup\$IniValue::TheGetProfileString()
betweennew
anddelete
can throw an exception - you have a memleak (defstr
). \$\endgroup\$