mirror of
https://github.com/bkthomps/Containers.git
synced 2025-12-26 09:09:08 +00:00
Fix bug reported in Issue #16
Before this bug was fixed, it would result in a segmentation fault due to an off-by-one error in the trim function in the deque file. This off by one error was due to the fact that the end index points to the index after the last allocated block. However, in the trim function, the end index was treated as the last allocated block. Thus, in the case that the last block was completely full, the trim function would function as if there were another block after that block with one item in it. Thus, this block would be copied from without the memory being allocated.
This commit is contained in:
@@ -113,7 +113,7 @@ bool deque_is_empty(deque me)
|
||||
int deque_trim(deque me)
|
||||
{
|
||||
const int start_block = me->start_index / BLOCK_SIZE;
|
||||
const int end_block = me->end_index / BLOCK_SIZE;
|
||||
const int end_block = (me->end_index - 1) / BLOCK_SIZE;
|
||||
const int new_block_count = end_block - start_block + 1;
|
||||
void *const new_block = malloc(new_block_count * sizeof(struct node));
|
||||
if (!new_block) {
|
||||
@@ -127,9 +127,9 @@ int deque_trim(deque me)
|
||||
const struct node block_item = me->block[i];
|
||||
free(block_item.data);
|
||||
}
|
||||
memmove(new_block,
|
||||
&me->block[start_block],
|
||||
new_block_count * sizeof(struct node));
|
||||
memcpy(new_block,
|
||||
&me->block[start_block],
|
||||
new_block_count * sizeof(struct node));
|
||||
free(me->block);
|
||||
me->block = new_block;
|
||||
me->block_count = new_block_count;
|
||||
|
||||
@@ -106,4 +106,11 @@ void test_deque(void)
|
||||
assert(deque_is_empty(me));
|
||||
me = deque_destroy(me);
|
||||
assert(!me);
|
||||
// Testing automatic trim
|
||||
me = deque_init(sizeof(int));
|
||||
for (int i = 0; i < 100; i++) {
|
||||
deque_push_back(me, &i);
|
||||
deque_pop_front(&get, me);
|
||||
}
|
||||
deque_destroy(me);
|
||||
}
|
||||
|
||||
@@ -52,4 +52,11 @@ void test_queue(void)
|
||||
}
|
||||
assert(pop_count == old_size);
|
||||
queue_destroy(me);
|
||||
// Testing automatic trim
|
||||
me = queue_init(sizeof(int));
|
||||
for (int i = 0; i < 100; i++) {
|
||||
queue_push(me, &i);
|
||||
queue_pop(&get, me);
|
||||
}
|
||||
queue_destroy(me);
|
||||
}
|
||||
|
||||
@@ -35,4 +35,11 @@ void test_stack(void)
|
||||
assert(!stack_top(&get, me));
|
||||
me = stack_destroy(me);
|
||||
assert(!me);
|
||||
// Testing automatic trim
|
||||
me = stack_init(sizeof(int));
|
||||
for (int i = 0; i < 100; i++) {
|
||||
stack_push(me, &i);
|
||||
stack_pop(&get, me);
|
||||
}
|
||||
stack_destroy(me);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user