Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix undefined behavior in memory allocation #626

Merged
merged 1 commit into from
Oct 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions mem/mem.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,6 @@
#include <cstdlib>
#include <type_traits>

template<typename T> static inline T *mem_rmalloc()
{
static_assert(std::is_trivially_constructible_v<T> && std::is_trivially_destructible_v<T>);
return static_cast<T *>(std::malloc(sizeof(T)));
}
template<typename T> static inline T *mem_rmalloc(std::size_t nelem)
{
static_assert(std::is_trivially_constructible_v<T> && std::is_trivially_destructible_v<T>);
return static_cast<T *>(std::malloc(nelem * sizeof(T)));
}

// Memory management debugging
#ifdef MEM_USE_RTL
#define mem_malloc(d) malloc(d) // Use this if your going to run BoundsChecker
Expand All @@ -106,10 +95,10 @@ template<typename T> static inline T *mem_rmalloc(std::size_t nelem)
extern bool Mem_low_memory_mode;
extern bool Mem_superlow_memory_mode; // DAJ

// use if you want to manually print out a memory error
// use if you want to manually print out a memory error
#define mem_error() mem_error_msg(__FILE__, __LINE__)

// initializes memory library.
// initializes memory library.
void mem_Init();

// shutsdown memory
Expand All @@ -124,7 +113,7 @@ void *mem_malloc_sub(int size, const char *file, int line);
// Frees a previously allocated block of memory
void mem_free_sub(void *memblock);

// prints out a memory error message
// prints out a memory error message
void mem_error_msg(const char *file, int line, int size = -1);

char *mem_strdup_sub(const char *src, const char *file, int line);
Expand All @@ -137,4 +126,16 @@ bool mem_dumpmallocstofile(char *filename);

void mem_heapcheck();

// type aware memory allocation
template<typename T> static inline T *mem_rmalloc()
{
static_assert(std::is_trivially_constructible_v<T> && std::is_trivially_destructible_v<T>);
return static_cast<T *>(mem_malloc(sizeof(T)));
}
template<typename T> static inline T *mem_rmalloc(std::size_t nelem)
{
static_assert(std::is_trivially_constructible_v<T> && std::is_trivially_destructible_v<T>);
return static_cast<T *>(mem_malloc(nelem * sizeof(T)));
}

#endif
Loading