Skip to content

Changed sprintf to snprintf in MemoryOutStream::FormatToStream. #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/MemoryOutStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ void FormatToStream(MemoryOutStream& stream, char const* format, ValueType const
{
using namespace std;

char txt[32];
sprintf(txt, format, value);
const size_t BUFFER_SIZE=32;
char txt[BUFFER_SIZE];
snprintf(txt, BUFFER_SIZE, format, value);
stream << txt;
}

Expand Down Expand Up @@ -127,7 +128,7 @@ MemoryOutStream& MemoryOutStream::operator <<(unsigned long long const n)

MemoryOutStream& MemoryOutStream::operator <<(float const f)
{
FormatToStream(*this, "%ff", f);
FormatToStream(*this, "%0.6f", f);
return *this;
}

Expand All @@ -145,7 +146,7 @@ MemoryOutStream& MemoryOutStream::operator <<(unsigned int const s)

MemoryOutStream& MemoryOutStream::operator <<(double const d)
{
FormatToStream(*this, "%f", d);
FormatToStream(*this, "%0.6f", d);
return *this;
}

Expand Down
14 changes: 11 additions & 3 deletions src/tests/TestMemoryOutStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cfloat>

using namespace UnitTest;
using namespace std;
Expand Down Expand Up @@ -152,15 +153,15 @@ TEST(WritingStringLongerThanCapacityFitsInNewBuffer)
TEST(WritingIntLongerThanCapacityFitsInNewBuffer)
{
MemoryOutStream stream(8);
stream << "aaaa" << 123456;;
stream << "aaaa" << 123456;
CHECK_EQUAL("aaaa123456", stream.GetText());
}

TEST(WritingFloatLongerThanCapacityFitsInNewBuffer)
{
MemoryOutStream stream(8);
stream << "aaaa" << 123456.0f;;
CHECK_EQUAL("aaaa123456.000000f", stream.GetText());
stream << "aaaa" << 123456.0f;
CHECK_EQUAL("aaaa123456.000000", stream.GetText());
}

TEST(WritingSizeTLongerThanCapacityFitsInNewBuffer)
Expand All @@ -170,6 +171,13 @@ TEST(WritingSizeTLongerThanCapacityFitsInNewBuffer)
CHECK_EQUAL("aaaa32145", stream.GetText());
}

TEST(VerifyLargeDoubleCanBeStreamedWithoutCrashing)
{
MemoryOutStream stream(8);
stream << DBL_MAX;
CHECK(true);
}

#endif

}