@@ -149,19 +149,17 @@ ZTEST(k_heap_api, test_k_heap_alloc_fail)
149
149
k_heap_free (& k_heap_test , p );
150
150
}
151
151
152
-
153
152
/**
154
153
* @brief Test k_heap_free() API functionality.
155
154
*
156
155
* @ingroup k_heap_api_tests
157
156
*
158
- * @details The test validates k_heap_free()
159
- * API, by using below steps
157
+ * @details The test validates k_heap_free() API, by using below steps
160
158
* 1. allocate the memory from the heap,
161
- * 2. free the allocated memory
162
- * 3. allocate memory more than the first allocation.
163
- * the allocation in the 3rd step should succeed if k_heap_free()
164
- * works as expected
159
+ * 2. free a NULL pointer (should have no effect)
160
+ * 3. free the allocated memory
161
+ * 4. allocate memory more than the first allocation.
162
+ * The allocation in the 4th step should succeed if k_heap_free() works as expected
165
163
*
166
164
* @see k_heap_alloc, k_heap_free()
167
165
*/
@@ -171,6 +169,10 @@ ZTEST(k_heap_api, test_k_heap_free)
171
169
char * p = (char * )k_heap_alloc (& k_heap_test , ALLOC_SIZE_1 , timeout );
172
170
173
171
zassert_not_null (p , "k_heap_alloc operation failed" );
172
+
173
+ /* Free NULL pointer: should not crash or corrupt heap */
174
+ k_heap_free (& k_heap_test , NULL );
175
+
174
176
k_heap_free (& k_heap_test , p );
175
177
p = (char * )k_heap_alloc (& k_heap_test , ALLOC_SIZE_2 , timeout );
176
178
zassert_not_null (p , "k_heap_alloc operation failed" );
@@ -477,3 +479,35 @@ ZTEST(k_heap_api, test_k_heap_aligned_alloc)
477
479
*/
478
480
ztest_test_fail ();
479
481
}
482
+
483
+ /*
484
+ * should be run last because the double-freeing corrupts memory
485
+ * (hence the prefix z_ in the test's name)
486
+ */
487
+ /**
488
+ * @brief Test k_heap_free() API double free edge case.
489
+ *
490
+ * @ingroup k_heap_api_tests
491
+ *
492
+ * @details The test validates that double-freeing a pointer asserts
493
+ *
494
+ * @see k_heap_alloc, k_heap_free()
495
+ */
496
+ ZTEST (k_heap_api , test_z_k_heap_double_free )
497
+ {
498
+ k_timeout_t timeout = Z_TIMEOUT_US (TIMEOUT );
499
+ char * p = (char * )k_heap_alloc (& k_heap_test , ALLOC_SIZE_1 , timeout );
500
+
501
+ zassert_not_null (p , "k_heap_alloc operation failed" );
502
+
503
+ k_heap_free (& k_heap_test , p );
504
+
505
+ ztest_set_fault_valid (true);
506
+ /* Double free: should assert */
507
+ k_heap_free (& k_heap_test , p );
508
+ /*
509
+ * If calling k_heap_free twice on the same buffer didn't result in an assert
510
+ * then the API isn't working as expected, and the test shall fail.
511
+ */
512
+ ztest_test_fail ();
513
+ }
0 commit comments