Follow Me on Twitter

Friday, October 30, 2009

Solutions to C Puzzles 4

What is the potential problem with the following C program?
  #include 
int main()
{
char str[80];
printf("Enter the string:");
scanf("%s",str);
printf("You entered:%s\n",str);

return 0;
}

Solution:

Buffer overflow problem. Since C doesn't do bound checking, anyone can fill more
than 80 characters. Hackers might use this to overwrite the return address and
cause malicious activities.

What is the output of the following program?
#include
int main()
{
int i;
i = 1,2,3;
printf("i:%d\n",i);
return 0;
}

Solution:
i: 1


What is the output of the following program?
#include
int main()
{
int cnt = 5, a;

do {
a /= cnt;
} while (cnt --);

printf ("%d\n", a);
return 0;
}


Solution:

Division by 0 exception.


In the while loop, first the condition is checked and then the value is decremented.
i.e first the existing value of cnt is used to check the truthfulness of while loop
and then the value of cnt is decremented before the execution enters the body of
the loop. Hence when cnt is 1, while return true but the value of cnt at a/=cnt
would be 0 and hence causes run time error.

What is the output of the following program?
#include
int main()
{
int i = 6;
if( ((++i < 7) && ( i++/6)) || (++i <= 9))
;
printf("%d\n",i);
return 0;
}

Solution:
8

Only ((++i < 7) && ( i++/6)) this gets executed. here first the value is tested and
then incremented.
(++i < 7) this is true bcs 6< style="color:#008b8b;">i++/6) is true
bcs 7/6 is 1 and now i=8. Since if includes ||(or) if once condition is true,
the remaining condition won't be checked.

What is the output of the following, if the input provided is:

Life is beautiful
#include
int main()
{
char dummy[80];
printf("Enter a string:\n");
scanf("%[^a]",dummy);
printf("%s\n",dummy);
return 0;
}

Solution:
Life is be


in the above scanf statement, it accepts the input from the stdin(standard input)
till it encounters character "a"( small a)

No comments:

Post a Comment