Each program misuses a library function: some are rejected by the compiler, others corrupt memory or give wrong results. Choose the option that names the real problem.
Question 1Easy
The program below has a bug. Which statement correctly describes it?
main.c
#include <stdio.h>
int main(void) {
double side = 49;
printf("%.1f\n", sqrt(side));
return 0;
}
Aside must be an int
Bsqrt is used without its declaration – <math.h> is not included
C%.1f cannot print a double
DThere is no bug
Correct Answer: Option B
Since C99 an undeclared function cannot be called. Before that the compiler assumed it returned int, which gave garbage for double results.
The program below has a bug. Which statement correctly describes it?
main.c
#include <stdio.h>
#include <stdlib.h>
int cmp(int *a, int *b) {
return *a - *b;
}
int main(void) {
int v[] = {3, 1, 2};
qsort(v, 3, sizeof v[0], cmp);
printf("%d %d %d\n", v[0], v[1], v[2]);
return 0;
}
Aqsort cannot sort ints
BThe comparator must have the type int (*)(const void *, const void *); a function taking int * is an incompatible pointer type
Csizeof v[0] should be sizeof v
DThere is no bug
Correct Answer: Option B
Write int cmp(const void *a, const void *b) and convert inside: int x = *(const int *) a;. Also prefer (x > y) - (x < y) to subtraction, which can overflow.
The program below has a bug. Which statement correctly describes it?
main.c
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "hello world";
memcpy(text + 1, text, 5); /* shift right by one */
printf("%s\n", text);
return 0;
}
Amemcpy needs strlen
BSource and destination overlap, which is undefined behaviour for memcpy – memmove must be used
Ctext is read-only
DThere is no bug
Correct Answer: Option B
Some memcpy implementations copy blocks forward or backward for speed, so the result can be wrong or (with sanitizers) the program is stopped. memmove(text + 1, text, 5) is correct.
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·