Rajesh Rajesh - 1 month ago 16
C Question

while loop is not breaking

I am not able to find out the reason for the misbehavior of the below code. This is a simple code to accept characters until either * is entered or until array size is reached and then print the characters read from the keyboard. It looks like the reading part is fine. Also if I enter * before array size is reached everything is OK. But if I do not enter * and wait until array size is reached in reading portion, I have the trouble. While printing it prints the characters read, but after that some garbage is printed. Ran through debugger, but while loop is not breaking when index is 3 or more.

int main()
{
char myStr [3];
unsigned int index=0;
printf("Enter Single characters. Enter * to stop\n");
do
{
scanf(" %c",&myStr[index]);
index++;
} while ((myStr[index-1]!='*')&&((index)<(sizeof(myStr)/sizeof(myStr[0]))));

index=0;

while ((myStr[index]!='*')&&(index<(sizeof(myStr)/sizeof(myStr[0]))))
{
printf("%c",myStr[index]);
index++;
}
printf("\n");

return(0);
}

alk alk
Answer

The code runs into undefined behaviour on the printf loop's last iteration here

    while ((myStr[index]!='*')&&(index<(sizeof(myStr)/sizeof(myStr[0]))))
    {
      ...

as it in fact is doing

    while ((myStr[3] ....

with myStr[3] accessing myStr out-of-bounds.

To fix this do:

    while ((index < (sizeof(myStr)/sizeof(myStr[0]))) && (myStr[index] != '*'))

Boolean short-circuiting will take care of myStr[3] not being executed.