MultipleStack
is a class the supports multiple stacks, but stores all their values in a single one-dimensional array. push(item, k)
pushes the item
onto the k
stack. In order to do this correctly, the class stores an array top
that stores the index of the top most element of every stack. push
is supposed to increment top[k - 1]
by one after pushing item
so that the following items get pushed correctly. However, sometimes, push
increases top[k - 1]
by two and I am unable to figure out why.
#include <cassert>
class MultipleStack {
int * _s;
size_t * _top;
size_t _nStacks, _size;
public:
MultipleStack(size_t nStacks, size_t size) {
_nStacks = nStacks;
_size = size * nStacks;
_s = new int[size];
_top = new size_t[nStacks];
//Simply sets top = {0, 10, 20, ...} no error here
for (size_t i = 0; i < nStacks; i++) {
_top[i] = (_size / _nStacks) * i;
}
}
//This is the buggy method
void push(int item, size_t k) {
size_t beforeSet = _top[k - 1];
_s[_top[k - 1]] = item;
size_t afterSet = _top[k - 1];
assert(beforeSet == afterSet); // Fails when beforeSet = 14
_top[k - 1] = _top[k - 1] + 1;
}
static void testImplementation() {
//Both, nStacks and size, must be >= 9
int nStacks = 10;
int size = 10;
MultipleStack ms(nStacks, size);
for (int i = 1; i <= nStacks; i++) {
for (int j = 0; j < size; j++) {
ms.push(1, i);
}
}
}
};
int main(int argc, const char * argv[]) {
MultipleStack::testImplementation();
return 0;
}
I apologise for the lengthy code sample. I stripped out as much as I could, but I was unable to simply it further.
I see one bug in this line in c-tor:
_s = new int[size];
If i understand correctly, the _s represents the memory block for all the stacks, so it' size should be: size * nStacks
instead. This possibly leads to writing outside of the allocated memory, which overwrites the subsequent data ( _top
array is one of those data). Fix the _s
allocation and you should be good.
And next time try naming your variables in a more careful way, so you don't mistake size
and _size
so easily. This would not have been an issue if you renamed _size
-> _sizeOfAllStacks
or something along those lines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.