Fixed buffer overrun in spdylay_pq_push

This commit is contained in:
Tatsuhiro Tsujikawa 2012-05-24 21:35:27 +09:00
parent 31ff69ed07
commit a18f04e8c7
2 changed files with 17 additions and 3 deletions

View File

@ -27,7 +27,7 @@
int spdylay_pq_init(spdylay_pq *pq, spdylay_compar compar) int spdylay_pq_init(spdylay_pq *pq, spdylay_compar compar)
{ {
pq->capacity = 4096; pq->capacity = 4096;
pq->q = malloc(pq->capacity); pq->q = malloc(pq->capacity * sizeof(void*));
if(pq->q == NULL) { if(pq->q == NULL) {
return SPDYLAY_ERR_NOMEM; return SPDYLAY_ERR_NOMEM;
} }
@ -65,7 +65,8 @@ static void bubble_up(spdylay_pq *pq, size_t index)
int spdylay_pq_push(spdylay_pq *pq, void *item) int spdylay_pq_push(spdylay_pq *pq, void *item)
{ {
if(pq->capacity <= pq->length) { if(pq->capacity <= pq->length) {
void *nq = realloc(pq->q, pq->capacity*2); void *nq;
nq = realloc(pq->q, (pq->capacity*2) * sizeof(void*));
if(nq == NULL) { if(nq == NULL) {
return SPDYLAY_ERR_NOMEM; return SPDYLAY_ERR_NOMEM;
} }

View File

@ -35,6 +35,7 @@ static int pq_compar(const void *lhs, const void *rhs)
void test_spdylay_pq(void) void test_spdylay_pq(void)
{ {
int i;
spdylay_pq pq; spdylay_pq pq;
spdylay_pq_init(&pq, pq_compar); spdylay_pq_init(&pq, pq_compar);
CU_ASSERT(spdylay_pq_empty(&pq)); CU_ASSERT(spdylay_pq_empty(&pq));
@ -60,7 +61,19 @@ void test_spdylay_pq(void)
spdylay_pq_pop(&pq); spdylay_pq_pop(&pq);
CU_ASSERT(spdylay_pq_empty(&pq)); CU_ASSERT(spdylay_pq_empty(&pq));
CU_ASSERT(0 == spdylay_pq_size(&pq)); CU_ASSERT(0 == spdylay_pq_size(&pq));
CU_ASSERT(0 == spdylay_pq_top(&pq)); CU_ASSERT(NULL == spdylay_pq_top(&pq));
/* Add bunch of entry to see realloc works */
for(i = 0; i < 10000; ++i) {
CU_ASSERT(0 == spdylay_pq_push(&pq, (void*)"foo"));
CU_ASSERT(i+1 == spdylay_pq_size(&pq));
}
for(i = 10000; i > 0; --i) {
CU_ASSERT(NULL != spdylay_pq_top(&pq));
spdylay_pq_pop(&pq);
CU_ASSERT(i-1 == spdylay_pq_size(&pq));
}
spdylay_pq_free(&pq); spdylay_pq_free(&pq);
} }