Skip to content

Commit e5c6168

Browse files
Fix instantiation and array accesses in class base_uint<BITS>
The implementation of base_uint::operator++(int) and base_uint::operator--(int) is now safer. Array pn is accessed via index i after bounds checking has been performed on the index, rather than before. The logic of the while loops has also been made more clear. A compile time assertion has been added in the class constructors to ensure that BITS is a positive multiple of 32.
1 parent 46311e7 commit e5c6168

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/arith_uint256.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
template <unsigned int BITS>
1616
base_uint<BITS>::base_uint(const std::string& str)
1717
{
18+
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
19+
1820
SetHex(str);
1921
}
2022

src/arith_uint256.h

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,16 @@ class base_uint
3131

3232
base_uint()
3333
{
34+
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
35+
3436
for (int i = 0; i < WIDTH; i++)
3537
pn[i] = 0;
3638
}
3739

3840
base_uint(const base_uint& b)
3941
{
42+
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
43+
4044
for (int i = 0; i < WIDTH; i++)
4145
pn[i] = b.pn[i];
4246
}
@@ -50,6 +54,8 @@ class base_uint
5054

5155
base_uint(uint64_t b)
5256
{
57+
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
58+
5359
pn[0] = (unsigned int)b;
5460
pn[1] = (unsigned int)(b >> 32);
5561
for (int i = 2; i < WIDTH; i++)
@@ -174,7 +180,7 @@ class base_uint
174180
{
175181
// prefix operator
176182
int i = 0;
177-
while (++pn[i] == 0 && i < WIDTH-1)
183+
while (i < WIDTH && ++pn[i] == 0)
178184
i++;
179185
return *this;
180186
}
@@ -191,7 +197,7 @@ class base_uint
191197
{
192198
// prefix operator
193199
int i = 0;
194-
while (--pn[i] == (uint32_t)-1 && i < WIDTH-1)
200+
while (i < WIDTH && --pn[i] == (uint32_t)-1)
195201
i++;
196202
return *this;
197203
}

0 commit comments

Comments
 (0)