Skip to content

Commit e0515ae

Browse files
committed
Fix q_insert_head and q_insert_tail
Previously, the implementation stored string pointers directly, causing issues when multiple elements shared the same memory reference. This led to test failures checking whether strings were properly copied. This fix ensures each queue element allocates and copies its own string, preventing unintended modifications across elements. Also, added proper cleanup in case of allocation failure. Change-Id: Ic01c44fcab94b30eb8fbb31b7c85cd8e83c1c567
1 parent f78288d commit e0515ae

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

queue.c

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,12 @@ bool q_insert_head(struct list_head *head, char *s)
3939
element_t *new_elem = malloc(sizeof(element_t));
4040
if (!new_elem)
4141
return false;
42-
new_elem->value = s;
42+
new_elem->value = malloc(strlen(s) + 1);
43+
if (!new_elem->value) {
44+
q_release_element(new_elem);
45+
return false;
46+
}
47+
strlcpy(new_elem->value, s, strlen(s) + 1);
4348
list_add(&new_elem->list, head);
4449
return true;
4550
}
@@ -52,7 +57,12 @@ bool q_insert_tail(struct list_head *head, char *s)
5257
element_t *new_elem = malloc(sizeof(element_t));
5358
if (!new_elem)
5459
return false;
55-
new_elem->value = s;
60+
new_elem->value = malloc(strlen(s) + 1);
61+
if (!new_elem->value) {
62+
q_release_element(new_elem);
63+
return false;
64+
}
65+
strlcpy(new_elem->value, s, strlen(s) + 1);
5666
list_add_tail(&new_elem->list, head);
5767
return true;
5868
}

0 commit comments

Comments
 (0)