Skip to content

Fix UB in priority_queue_pop#156

Open
Unknown-reader wants to merge 1 commit into
bkthomps:masterfrom
Unknown-reader:fix/priority-queue-pop-overlap
Open

Fix UB in priority_queue_pop#156
Unknown-reader wants to merge 1 commit into
bkthomps:masterfrom
Unknown-reader:fix/priority-queue-pop-overlap

Conversation

@Unknown-reader
Copy link
Copy Markdown

Description

This PR fixes an undefined behavior in the priority_queue_pop function caused by memcpy being called with overlapping memory regions. This occurs when the priority queue contains exactly one element.

Problem

In src/priority_queue.c, line 170, memcpy is used to copy the last element to the root of the heap:

temp = vector_storage + size * me->data_size;
memcpy(vector_storage, temp, me->data_size);

When the queue contains only one element (size == 0), both temp and vector_storage point to the same memory address, resulting in a memcpy call with identical src and dest pointers. This is undefined behavior according to the C standard.

Fix

Replaced the unsafe memcpy on line 170 with memmove, which is specifically designed to handle overlapping memory regions correctly. No other changes were necessary, as the other memcpy calls in the function operate on non-overlapping memory regions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant