All C Interview Questions

What is undefined behavior in C?

Undefined behavior (UB) means the C standard gives no rule about what the program will do. It may work, crash, or give a wrong result, and it can change with the compiler or the options.

Common examples:

  • Reading an uninitialized variable.
  • Accessing an array outside its limits.
  • Dereferencing a NULL or dangling pointer.
  • Signed integer overflow, like INT_MAX + 1.
  • Modifying a variable two times in one expression, like i = i++ + ++i.
  • Dividing by zero.

The danger is that the program may look fine on your computer. Compile with -Wall -Wextra and use -fsanitize=undefined to catch many of them.

Why should we not use the gets() function in C?

gets() reads a line but has no way to know the size of the array. If the user types more characters than the array can hold, the extra characters are written outside the array. This is a buffer overflow, and attackers can use it. The function was removed from the C11 standard.

#include <stdio.h>

int main(void) {
    char name[10];

    fgets(name, sizeof(name), stdin);   // reads at most 9 characters
    printf("%s", name);
    return 0;
}

fgets() takes the size, so it is safe. Note that it keeps the new line character. See String Input and Output.

What is the difference between int main() and int main(void) in C?

In C, int main() says nothing about the parameters, so the function can be called with any arguments (in older C standards). int main(void) clearly says that it takes no parameters. So int main(void) is the better and safer form.

If you want the command line arguments, use int main(int argc, char *argv[]). See Command Line Arguments.

Note that in C++ both forms mean the same thing. Also void main() is not standard, so always use int.

What is the difference between a macro and a function in C?

MacroFunction
Text replace by the preprocessorCompiled code that is called
No type checkingTypes are checked
Code is copied at each use (bigger program)One copy of the code
Faster, no call overheadSmall call overhead
Arguments can run two times (SQUARE(i++))Arguments are evaluated once

Use a function when you can. Use macros for constants and small tricks only. See Preprocessor and Macros.