[Concept,02/14] alist: Zero new entries in alist_add_placeholder()
Commit Message
From: Simon Glass <sjg@chromium.org>
It is convenient for alist_add_placeholder() to zero the entry before
returning it. This saves callers from needing to do it themselves.
Update an alist test to verify the new entry is zeroed.
Signed-off-by: Simon Glass <sjg@chromium.org>
---
include/alist.h | 7 +++----
lib/alist.c | 8 +++++++-
test/lib/alist.c | 10 ++++++++++
3 files changed, 20 insertions(+), 5 deletions(-)
--
2.43.0
@@ -174,12 +174,11 @@ void *alist_ensure_ptr(struct alist *lst, uint index);
((_struct *)alist_ensure_ptr(_lst, _index))
/**
- * alist_add_placeholder() - Add a new item to the end of the list
+ * alist_add_placeholder() - Add a new zeroed item to the end of the list
*
* @lst: alist to add to
- * Return: Pointer to the newly added position, or NULL if out of memory. Note
- * that this is not inited so the caller must copy the requested struct to the
- * returned pointer
+ * Return: Pointer to the newly added position (zeroed), or NULL if out of
+ * memory
*/
void *alist_add_placeholder(struct alist *lst);
@@ -165,7 +165,13 @@ void *alist_ensure_ptr(struct alist *lst, uint index)
void *alist_add_placeholder(struct alist *lst)
{
- return alist_ensure_ptr(lst, lst->count);
+ void *ptr;
+
+ ptr = alist_ensure_ptr(lst, lst->count);
+ if (ptr)
+ memset(ptr, '\0', lst->obj_size);
+
+ return ptr;
}
void *alist_add_ptr(struct alist *lst, void *obj)
@@ -219,8 +219,18 @@ static int lib_test_alist_add(struct unit_test_state *uts)
ut_asserteq(123, ptr->val);
ut_asserteq(456, ptr->other_val);
+ /* Add a non-zero entry then remove it, so the memory is dirty */
ptr2 = alist_add_placeholder(&lst);
ut_assertnonnull(ptr2);
+ ptr2->val = 999;
+ ptr2->other_val = 888;
+ lst.count--;
+
+ /* Now add again — the slot should be zeroed despite dirty memory */
+ ptr2 = alist_add_placeholder(&lst);
+ ut_assertnonnull(ptr2);
+ ut_asserteq(0, ptr2->val);
+ ut_asserteq(0, ptr2->other_val);
ptr2->val = 321;
ptr2->other_val = 654;