Skip to content

Commit c9212e2

Browse files
authored
Align tflite::BufferPlan properly (#2698)
In the non_persistent_buffer_planner_shim_test, a tflite::BufferPlan is created using a statically allocated buffer. A static array is allocated and the address of it is used with a reinterpret_cast. This is undefined behavior, as it could result in misaligned member accesses. This PR forces the statically allocated array to align as if it was a tflite::BufferPlan, and then uses placement new to construct it within the buffer. BUG=none
1 parent e8e7853 commit c9212e2

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

tensorflow/lite/micro/memory_planner/non_persistent_buffer_planner_shim_test.cc

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,10 @@ tflite::BufferPlan* CreateBufferPlan() {
3434
// Some targets do not support dynamic memory (i.e., no malloc or new), thus,
3535
// the test need to place non-transitent memories in static variables. This is
3636
// safe because tests are guarateed to run serially.
37-
static int8_t buffer_plan_buffer[tflite::SizeOfBufferPlan(kBufferCnt)];
37+
alignas(tflite::BufferPlan) static int8_t
38+
buffer_plan_buffer[tflite::SizeOfBufferPlan(kBufferCnt)];
3839
tflite::BufferPlan* buffer_plan_ptr =
39-
reinterpret_cast<tflite::BufferPlan*>(buffer_plan_buffer);
40+
new (buffer_plan_buffer) tflite::BufferPlan();
4041
buffer_plan_ptr->buffer_count = kBufferCnt;
4142
buffer_plan_ptr->buffer_plan_entries[0].offset = kBuffer0Offset;
4243
buffer_plan_ptr->buffer_plan_entries[1].offset = kBuffer1Offset;

0 commit comments

Comments
 (0)