From 92eef5395ce7d6a3c8334d9195e9ac9d95eebf96 Mon Sep 17 00:00:00 2001 From: ocsmit Date: Mon, 17 Jul 2023 17:18:04 -0400 Subject: [PATCH] Update src, bounds checking --- src/bitarr.c | 5 +---- src/bitarr.h | 2 +- src/bitops.c | 8 ++++++++ 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/bitarr.c b/src/bitarr.c index fa48330..f38dcf3 100644 --- a/src/bitarr.c +++ b/src/bitarr.c @@ -3,9 +3,7 @@ BitArray* BitArray_calloc(unsigned int n, unsigned int l) { - // Ceiling division - unsigned int n_entries = (l * n)/WORD_SIZE + ((l*n) % WORD_SIZE != 0); - + unsigned int n_entries = 1 + (((l * n) - 1) / WORD_SIZE); // space for bitarray + space needed for n_entries of word_size BitArray *bitarr = calloc(1, sizeof(BitArray) + WORD_SIZE * n_entries); if (bitarr == NULL) { @@ -33,4 +31,3 @@ BitArray* BitArray_init(unsigned int A[], unsigned int n, unsigned int l) for (i = 0; i < n; ++i) BitArray_write(bit_arr, i, A[i]); return bit_arr; } - diff --git a/src/bitarr.h b/src/bitarr.h index 3475d1a..3012cdc 100644 --- a/src/bitarr.h +++ b/src/bitarr.h @@ -113,7 +113,7 @@ typedef struct { * @param l Size in bits of each item * @return Pointer to BitArray */ -BitArray* BitArray_calloc(unsigned int n_entries, unsigned int l); +BitArray* BitArray_calloc(unsigned int n, unsigned int l); /** * @brief Free BitArray allocated on the heap diff --git a/src/bitops.c b/src/bitops.c index a6b5b35..1dd355e 100644 --- a/src/bitops.c +++ b/src/bitops.c @@ -57,6 +57,10 @@ unsigned int BitArray_bitsread(BitArray* bit_arr, unsigned int j1, unsigned int unsigned int BitArray_read(BitArray* bit_arr, unsigned int i) { + if (i >= bit_arr->n) { + fprintf(stderr, "%s:%d Out of bounds index\n", __FILE__, __LINE__); + exit(OUT_OF_BOUNDS); + } return BitArray_bitsread(bit_arr, i*bit_arr->l, (i+1)*bit_arr->l-1); } @@ -92,5 +96,9 @@ void BitArray_bitswrite(BitArray* bit_arr, unsigned int j1, unsigned int j, unsi void BitArray_write(BitArray* bit_arr, unsigned int i, unsigned int x) { + if (i >= bit_arr->n) { + fprintf(stderr, "%s:%d Out of bounds index\n", __FILE__, __LINE__); + exit(OUT_OF_BOUNDS); + } BitArray_bitswrite(bit_arr, i*bit_arr->l, (i+1)*bit_arr->l-1, x); } -- 2.45.2