Skip to content

Commit 16872af

Browse files
committed
Avoid pointer arithmetic on null pointer to remove undefined behavior
The existing checks triggered undefined behavior when the stack was empty (null pointer). This change avoid this: * If `stackTop_` and `stackEnd_` are null, it results in a `ptrdiff_t` of `0` * If `stackTop_` and `stackEnd_` are valid pointers, they produce a `ptrdiff_t` with the remaining size on the stack
1 parent 663f076 commit 16872af

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

include/rapidjson/internal/stack.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
#include "../allocators.h"
1919
#include "swap.h"
20+
#include <cstddef>
2021

2122
#if defined(__clang__)
2223
RAPIDJSON_DIAG_PUSH
@@ -114,7 +115,7 @@ class Stack {
114115
template<typename T>
115116
RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) {
116117
// Expand the stack if needed
117-
if (RAPIDJSON_UNLIKELY(stackTop_ + sizeof(T) * count > stackEnd_))
118+
if (RAPIDJSON_UNLIKELY(static_cast<std::ptrdiff_t>(sizeof(T) * count) > (stackEnd_ - stackTop_)))
118119
Expand<T>(count);
119120
}
120121

@@ -127,7 +128,7 @@ class Stack {
127128
template<typename T>
128129
RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) {
129130
RAPIDJSON_ASSERT(stackTop_);
130-
RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_);
131+
RAPIDJSON_ASSERT(static_cast<std::ptrdiff_t>(sizeof(T) * count) <= (stackEnd_ - stackTop_));
131132
T* ret = reinterpret_cast<T*>(stackTop_);
132133
stackTop_ += sizeof(T) * count;
133134
return ret;

0 commit comments

Comments
 (0)