From c1496ab6c055974ac401865bdca87a4fc0a76ea3 Mon Sep 17 00:00:00 2001 From: bobsayshilol Date: Sun, 27 Oct 2024 20:11:42 +0000 Subject: [PATCH] Fix passing nullptr to args marked as non-null libstdc++'s |memcpy| and |memset| both state that their inputs should never be a nullptr since this matches the C spec. Some compilers act on these hints, so we shouldn't unconditionally call these as it would signal to the compiler that they can't be nullptrs. As an example, the following code will always call |do_something()| when compiled with optimisations since GCC version 4.9: ``` void clear(void *ptr, int size) { memset(ptr, 0, size); } void example(void *ptr, int size) { clear(ptr, size); if (ptr != nullptr) do_something(); } ``` --- src/gb/gb.h | 6 +++++- src/string.cpp | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/gb/gb.h b/src/gb/gb.h index 1fef4b4f5..f74026c7d 100644 --- a/src/gb/gb.h +++ b/src/gb/gb.h @@ -2541,7 +2541,11 @@ gb_inline void const *gb_pointer_add_const(void const *ptr, isize bytes) { gb_inline void const *gb_pointer_sub_const(void const *ptr, isize bytes) { return cast(void const *)(cast(u8 const *)ptr - bytes); } gb_inline isize gb_pointer_diff (void const *begin, void const *end) { return cast(isize)(cast(u8 const *)end - cast(u8 const *)begin); } -gb_inline void gb_zero_size(void *ptr, isize size) { memset(ptr, 0, size); } +gb_inline void gb_zero_size(void *ptr, isize size) { + if (size != 0) { + memset(ptr, 0, size); + } +} #if defined(_MSC_VER) && !defined(__clang__) diff --git a/src/string.cpp b/src/string.cpp index 3c7d96934..190b69041 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -156,6 +156,7 @@ gb_internal isize string_index_byte(String const &s, u8 x) { gb_internal gb_inline bool str_eq(String const &a, String const &b) { if (a.len != b.len) return false; + if (a.len == 0) return true; return memcmp(a.text, b.text, a.len) == 0; } gb_internal gb_inline bool str_ne(String const &a, String const &b) { return !str_eq(a, b); }