From d58dada31e8387a1070d7bd49c0c90a1463f01eb Mon Sep 17 00:00:00 2001 From: robos Date: Fri, 19 Aug 2022 16:34:16 +0100 Subject: [PATCH] fixed undefined behaviour (changing twice between sequence points --- README.md | 2 +- dynamicFifo.tpp | 8 +++++--- example.cpp => examples/example.cpp | 6 +++++- 3 files changed, 11 insertions(+), 5 deletions(-) rename example.cpp => examples/example.cpp (96%) diff --git a/README.md b/README.md index c401f10..5be29de 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ For this reason, a check before popping is vital. (exampleFifo.fifo_status() == Fifo_STATUS::Fifo_EMPTY) ? /* Handle the fact that it's empty. */ : exampleFifo.pop(); ``` -See `example.cpp` for a more examples. +See `example.cpp` for more examples. ### Usage with Vector diff --git a/dynamicFifo.tpp b/dynamicFifo.tpp index e88da37..2f41bc9 100644 --- a/dynamicFifo.tpp +++ b/dynamicFifo.tpp @@ -56,11 +56,12 @@ Fifo_STATUS Fifo::push(const T& item) { } // otherwise: elem[nextFree] = item; - if (((nextFree+1) % sz) == endPointer) { + if (((nextFree+1) % sz) == static_cast(endPointer)) { nextFree = -1; } else{ - nextFree = (++nextFree) % sz; // wrap around /:) + nextFree++; + nextFree = (nextFree) % sz; // wrap around /:) } return Fifo_STATUS::Fifo_GOOD; } @@ -75,7 +76,8 @@ T Fifo::pop() { /// Note: You should check the status of the fifo before call if (fifo_status()==Fifo_STATUS::Fifo_FULL) { nextFree=endPointer; } - endPointer = (++endPointer) % sz; // wrap around /:) + endPointer++; + endPointer = (endPointer) % sz; // wrap around /:) return r; } diff --git a/example.cpp b/examples/example.cpp similarity index 96% rename from example.cpp rename to examples/example.cpp index 7307d9f..1e08af2 100644 --- a/example.cpp +++ b/examples/example.cpp @@ -87,7 +87,11 @@ int main() { // C-style casts. - does not resize the fifo. Fifo e2 = (Fifo) e1; - (e2.fifo_status() == Fifo_STATUS::Fifo_EMPTY) ? /* Handle the fact that it's empty. */ : e2.pop(); + + if (e2.fifo_status() == Fifo_STATUS::Fifo_EMPTY) + std::cout<<"It's empty"; + else + e2.pop(); std::cout << "e2 Free space: " << e2.free_space() << std::endl; #endif // DYNAMIC_FIFO_H