@@ -156,9 +156,11 @@ ZTEST(k_heap_api, test_k_heap_alloc_fail)
156
156
* @details The test validates k_heap_free()
157
157
* API, by using below steps
158
158
* 1. allocate the memory from the heap,
159
- * 2. free the allocated memory
160
- * 3. allocate memory more than the first allocation.
161
- * the allocation in the 3rd step should succeed if k_heap_free()
159
+ * 2. Freeing a NULL pointer (should have no effect)
160
+ * 3. free the allocated memory
161
+ * 4. allocate memory more than the first allocation.
162
+ * 5. Double-freeing a pointer (asserts, but should not crash)
163
+ * the allocation in the 4th step should succeed if k_heap_free()
162
164
* works as expected
163
165
*
164
166
* @see k_heap_alloc, k_heap_free()
@@ -169,13 +171,22 @@ ZTEST(k_heap_api, test_k_heap_free)
169
171
char * p = (char * )k_heap_alloc (& k_heap_test , ALLOC_SIZE_1 , timeout );
170
172
171
173
zassert_not_null (p , "k_heap_alloc operation failed" );
174
+
175
+ /* Free NULL pointer: should not crash or corrupt heap */
176
+ k_heap_free (& k_heap_test , NULL );
177
+
172
178
k_heap_free (& k_heap_test , p );
173
179
p = (char * )k_heap_alloc (& k_heap_test , ALLOC_SIZE_2 , timeout );
174
180
zassert_not_null (p , "k_heap_alloc operation failed" );
175
181
for (int i = 0 ; i < ALLOC_SIZE_2 ; i ++ ) {
176
182
p [i ] = '0' ;
177
183
}
178
184
k_heap_free (& k_heap_test , p );
185
+
186
+ #ifndef CONFIG_ASSERT
187
+ /* Double free: should not crash, but behavior is otherwise undefined */
188
+ k_heap_free (& k_heap_test , p );
189
+ #endif
179
190
}
180
191
181
192
/**
@@ -469,6 +480,5 @@ ZTEST(k_heap_api, test_k_heap_aligned_alloc)
469
480
* and proceeds, so this should not assert or necessarily fail.
470
481
*/
471
482
p = k_heap_aligned_alloc (& k_heap_test , 3 , 64 , K_NO_WAIT );
472
- /* Accept any result; just ensure no crash or assertion. */
473
483
(void )p ;
474
484
}
0 commit comments