don't leak memory when throwing an exception

This commit is contained in:
Axel Kohlmeyer
2024-08-20 01:15:53 -04:00
parent 8cfd856296
commit 02752ddf6a
4 changed files with 22 additions and 1 deletions

View File

@ -48,6 +48,7 @@ TextFileReader::TextFileReader(const std::string &filename, const std::string &f
fp = fopen(filename.c_str(), "r");
if (fp == nullptr) {
delete[] line;
throw FileReaderException(
fmt::format("cannot open {} file {}: {}", filetype, filename, utils::getsyserror()));
}
@ -74,7 +75,11 @@ TextFileReader::TextFileReader(FILE *fp, std::string filetype) :
filetype(std::move(filetype)), closefp(false), line(nullptr), fp(fp), ignore_comments(true)
{
set_bufsize(1024);
if (fp == nullptr) throw FileReaderException("Invalid file descriptor");
if (fp == nullptr) {
delete[] line;
line = nullptr;
throw FileReaderException("Invalid file descriptor");
}
}
/** Closes the file */
@ -90,6 +95,8 @@ TextFileReader::~TextFileReader()
void TextFileReader::set_bufsize(int newsize)
{
if (newsize < 100) {
delete[] line;
line = nullptr;
throw FileReaderException(
fmt::format("line buffer size {} for {} file too small, must be > 100", newsize, filetype));
}
@ -112,6 +119,8 @@ void TextFileReader::skip_line()
char *ptr = fgets(line, bufsize, fp);
if (ptr == nullptr) {
// EOF
delete[] line;
line = nullptr;
throw EOFException(fmt::format("Missing line in {} file!", filetype));
}
}