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:
Bailey Thompson
2018-07-15 12:29:54 -07:00
committed by GitHub
parent dd9e099605
commit e2ee62af08
4 changed files with 25 additions and 4 deletions

View File

@@ -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;

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}