I would like to preface this with I am a junior but relatively experienced developer, but with very little C experience.
I have this test method that is supposed to pass an array of characters to find the "O".
TEST(MyTest, ReturnIndexOfO)
{
Widget unitUnderTest;
char x = 'X';
char o = 'O';
char *row[4] = {&o, &x, &x, &x};
char *row2[4] = {&x, &o, &x, &x};
EXPECT_EQ(unitUnderTest.findEmptySpace(*row, 4), 0);
EXPECT_EQ(unitUnderTest.findEmptySpace(*row2,4 ), 1);
}
And this has properly invoked my findEmptySpace method, which is:
#define WHITE_SPACE 'O'
int Widget::findEmptySpace(char row[], int size)
{
cout << "The row under test is:\n";
for(int i = 0; i < size; i ) {
cout << row[i];
}
cout << "\n";
for(int i = 0; i < size; i ) {
if(row[i] == WHITE_SPACE) {
return i;
}
}
return -1;
}
But unfortunately, my output seems indicate that not all of the characters are being read by my findEmptySpace method:
The row under test is:
OX
The row under test is:
X
So even with the truncated data, my first test case passes, but the second test case fails. Any idea why I am not seeing the data correctly?
CodePudding user response:
This expression
Test.findEmptySpace(*row, 4)
is equivalent to the expression
Test.findEmptySpace(row[0], 4)
and the element row[0]
is a pointer with the value &o
that points to the o
of the type char
char o = 'O';.
So the function call (the inner loops within the function) with such parameters does not make a sense
It seems what you mean is the following
EXPECT_EQ(unitUnderTest.findEmptySpace(row, 4), 0);
and
#define WHITE_SPACE 'O'
int Widget::findEmptySpace(char * row[], int size)
{
cout << "The row under test is:\n";
for(int i = 0; i < size; i ) {
cout << *row[i];
}
cout << "\n";
for(int i = 0; i < size; i ) {
if( *row[i] == WHITE_SPACE) {
return i;
}
}
return -1;
}
CodePudding user response:
char *row[4] = {&o, &x, &x, &x};
This is not an "array of characters". This is an array of four pointers to characters.
unitUnderTest.findEmptySpace(*row, 4)
This passes the first one of these pointers, to findEmptySpace()
in its first parameter. The first pointer is a pointer to o
.
The second parameter to findEmptySpace()
is 4. That's what the above statement does in C .
The function findEmptySpace()
does the following:
for(int i = 0; i < size; i ) {
cout << row[i];
}
So it ends up printing the first four characters from the pointer that was passed to it.
The problem is that the passed in pointer is a pointer to just one character:
&o
That's the first pointer. And this function ends up trying to read the first four character from a pointer that's pointing to only one character.
This results in undefined behavior.