Skip to content

Commit

Permalink
Use strncpy instead of memcpy for safer access
Browse files Browse the repository at this point in the history
  • Loading branch information
zoo868e committed Mar 3, 2024
1 parent 0c59fb6 commit f8a0ec4
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions queue.c
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,11 @@ element_t *q_new_element(char *s)
element_t *new = malloc(sizeof(element_t));
if (!new)
return NULL;
unsigned int size = str_len(s);
new->value = malloc(size + 1);
new->value = strdup(s);
if (!new->value) {
free(new);
return NULL;
}
memcpy(new->value, s, size);
*(new->value + size) = '\0';
return new;
}

Expand Down Expand Up @@ -96,9 +93,11 @@ element_t *q_remove(struct list_head *head, char *sp, size_t bufsize)
if (!head)
return NULL;
element_t *ret = list_entry(head, element_t, list);
if (!ret)
return NULL;
list_del(head);
if (ret && sp && bufsize > 0) {
memcpy(sp, ret->value, bufsize - 1);
if (sp && bufsize - 1 > 0) {
strncpy(sp, ret->value, bufsize - 1);
*(sp + bufsize - 1) = '\0';
}
return ret;
Expand Down Expand Up @@ -199,8 +198,7 @@ void q_reverseK(struct list_head *head, int k)
LIST_HEAD(tmp);
int count = 0;
list_for_each_safe (cur, n, head) {
list_del(cur);
list_add(cur, &tmp);
list_move(cur, &tmp);
++count;
if (count == k) {
count = 0;
Expand Down

0 comments on commit f8a0ec4

Please sign in to comment.