Ashim Kapoor: Added function that returns minimum size of format strings (#694)

This commit is contained in:
Daniel Marjamäki 2009-09-25 18:23:44 +02:00
parent 2594f9b63f
commit fe3c8cab9f
3 changed files with 83 additions and 0 deletions

View File

@ -749,6 +749,70 @@ void CheckBufferOverrun::bufferOverrun()
//---------------------------------------------------------------------------
int CheckBufferOverrun::count(const std::string &input_string)
{
int flag = 1;
int input_string_size = 0;
int on_on_next = 0;
std::string digits_string = "";
int digits = 0;
for (std::string::size_type i = 0; i != input_string.size(); i++)
{
if (on_on_next == 1)
{
flag = 1;
on_on_next = 0;
}
switch (input_string[i])
{
case 'd':
case 'i':
case 'c':
case 'e':
case 'E':
case 'f':
case 'g':
case 'o':
case 's':
case 'u':
case 'x':
case 'X':
case 'p':
case 'n':
if (flag == 0) on_on_next = 1;
break;
case '%':
if (flag == 1) flag = 0;
break;
case '/':
input_string_size--;
break;
}
if (flag) input_string_size++;
else
digits_string += input_string[i];
if (on_on_next == 1 && flag == 0)
{
digits_string = digits_string.substr(1, digits_string.size());
digits += abs(atoi(digits_string.c_str()));
digits_string = "";
}
}
return input_string_size + 1 + digits;
}

View File

@ -56,6 +56,8 @@ public:
/** Check for buffer overruns */
void bufferOverrun();
static int count(const std::string &input_string);
private:
/** Check for buffer overruns - locate struct variables and check them with the .._CheckScope function */
@ -100,3 +102,5 @@ private:
//---------------------------------------------------------------------------
#endif

View File

@ -118,6 +118,7 @@ private:
TEST_CASE(alloc); // Buffer allocated with new
TEST_CASE(memset1);
TEST_CASE(counter_test);
}
@ -781,8 +782,22 @@ private:
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (possible error) The size argument is given as a char constant\n", errout.str());
}
void counter_test()
{
std::string str1 = "Hello";
std::string str2 = "Hello %2.2d %1d";
std::string str3 = "Test \" ";
ASSERT_EQUALS(6, CheckBufferOverrun::count(str1));
ASSERT_EQUALS(11, CheckBufferOverrun::count(str2));
ASSERT_EQUALS(8, CheckBufferOverrun::count(str3));
}
};
REGISTER_TEST(TestBufferOverrun)