c++tools: Fix memory leak
The allocated memory is not freed when returning early due to an error. c++tools/ChangeLog: * resolver.cc (module_resolver::read_tuple_file): Use unique_ptr to ensure memory is freed before returning.
This commit is contained in:
parent
7d37abedf5
commit
c9bf4d4354
|
@ -23,6 +23,7 @@ along with GCC; see the file COPYING3. If not see
|
||||||
#include "resolver.h"
|
#include "resolver.h"
|
||||||
// C++
|
// C++
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <memory>
|
||||||
// C
|
// C
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
// OS
|
// OS
|
||||||
|
@ -114,10 +115,17 @@ module_resolver::read_tuple_file (int fd, char const *prefix, bool force)
|
||||||
buffer = mmap (nullptr, stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
|
buffer = mmap (nullptr, stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||||
if (buffer == MAP_FAILED)
|
if (buffer == MAP_FAILED)
|
||||||
return -errno;
|
return -errno;
|
||||||
|
struct Deleter {
|
||||||
|
void operator()(void* p) const { munmap(p, size); }
|
||||||
|
size_t size;
|
||||||
|
};
|
||||||
|
std::unique_ptr<void, Deleter> guard(buffer, Deleter{(size_t)stat.st_size});
|
||||||
#else
|
#else
|
||||||
buffer = xmalloc (stat.st_size);
|
buffer = xmalloc (stat.st_size);
|
||||||
if (!buffer)
|
if (!buffer)
|
||||||
return -errno;
|
return -errno;
|
||||||
|
struct Deleter { void operator()(void* p) const { free(p); } };
|
||||||
|
std::unique_ptr<void, Deleter> guard(buffer);
|
||||||
if (read (fd, buffer, stat.st_size) != stat.st_size)
|
if (read (fd, buffer, stat.st_size) != stat.st_size)
|
||||||
return -errno;
|
return -errno;
|
||||||
#endif
|
#endif
|
||||||
|
@ -179,12 +187,6 @@ module_resolver::read_tuple_file (int fd, char const *prefix, bool force)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#if MAPPED_READING
|
|
||||||
munmap (buffer, stat.st_size);
|
|
||||||
#else
|
|
||||||
free (buffer);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue