diff options
author | Michael Lutz <michi@icosahedron.de> | 2020-12-06 21:11:48 +0100 |
---|---|---|
committer | Michael Lutz <michi@icosahedron.de> | 2020-12-27 13:19:25 +0100 |
commit | 024a3f62593fd783285c5ff09b8c85ee1fc34e2d (patch) | |
tree | 66673d58530d8c19272657678eb711dd29722e3a /src/fileio.cpp | |
parent | 5cbb2da79434ec002831bd72b2c81f9dcd469601 (diff) | |
download | openttd-024a3f62593fd783285c5ff09b8c85ee1fc34e2d.tar.xz |
Codechange: Use automatic memory management for language pack reading.
Diffstat (limited to 'src/fileio.cpp')
-rw-r--r-- | src/fileio.cpp | 29 |
1 files changed, 14 insertions, 15 deletions
diff --git a/src/fileio.cpp b/src/fileio.cpp index 5b8005929..5431df814 100644 --- a/src/fileio.cpp +++ b/src/fileio.cpp @@ -1236,28 +1236,27 @@ void SanitizeFilename(char *filename) * @return Pointer to new memory containing the loaded data, or \c nullptr if loading failed. * @note If \a maxsize less than the length of the file, loading fails. */ -void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize) +std::unique_ptr<char> ReadFileToMem(const std::string &filename, size_t &lenp, size_t maxsize) { - FILE *in = fopen(filename, "rb"); + FILE *in = fopen(filename.c_str(), "rb"); if (in == nullptr) return nullptr; + FileCloser fc(in); + fseek(in, 0, SEEK_END); size_t len = ftell(in); fseek(in, 0, SEEK_SET); - if (len > maxsize) { - fclose(in); - return nullptr; - } - byte *mem = MallocT<byte>(len + 1); - mem[len] = 0; - if (fread(mem, len, 1, in) != 1) { - fclose(in); - free(mem); - return nullptr; - } - fclose(in); + if (len > maxsize) return nullptr; + + /* std::unique_ptr assumes new/delete unless a custom deleter is supplied. + * As we don't want to have to carry that deleter all over the place, use + * new directly to allocate the memory instead of malloc. */ + std::unique_ptr<char> mem(static_cast<char *>(::operator new(len + 1))); + + mem.get()[len] = 0; + if (fread(mem.get(), len, 1, in) != 1) return nullptr; - *lenp = len; + lenp = len; return mem; } |