Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

C

Interview questions & answers

Pointers, memory, UB, preprocessor, standard library.

102 questions

  1. Question 1

    What is C?

    Low-level procedural language close to hardware; manual memory, minimal runtime; used for OS, embedded, and performance-critical systems.

    Example code

    #include <stdio.h>
    int main(void) { puts("C"); return 0; }
  2. Question 2

    What is a pointer?

    A variable holding a memory address of another object; * dereferences, & takes address of an lvalue.

    Example code

    int x = 42;
    int *p = &x;
    printf("%d\n", *p);
  3. Question 3

    NULL pointer?

    A pointer guaranteed to compare unequal to any valid object pointer; dereferencing is undefined behavior.

    Example code

    int *p = NULL;
  4. Question 4

    What is undefined behavior?

    The standard imposes no requirements—compilers may optimize assuming UB never happens; bugs can be non-deterministic.

    Example code

    // signed overflow is undefined
  5. Question 5

    What is implementation-defined behavior?

    Compiler must document choice (e.g. int size); differs by platform but must be consistent per implementation.

    Example code

    // int may be 32-bit
  6. Question 6

    Stack vs heap in C?

    Local auto variables often on stack; malloc allocates heap; lifetime and size differ—stack overflow vs heap exhaustion possible.

    Example code

    int a;
    int *h = malloc(sizeof *h);
  7. Question 7

    malloc vs calloc vs realloc?

    malloc uninitialized bytes; calloc zero-initializes; realloc resizes possibly moving the block—check return pointer.

    Example code

    void *m = malloc(16); memset(m, 0, 16); free(m);
  8. Question 8

    free rules?

    Only pointers from malloc family; double-free and use-after-free are UB—set pointer to NULL after free if needed for clarity.

    Example code

    free(p); p = NULL;
  9. Question 9

    What is a segmentation fault?

    Accessing invalid memory (often via bad pointer); OS kills process; debug with core dumps and sanitizers.

    Example code

    // segfault: *NULL
  10. Question 10

    const in C?

    Variables can't be assigned after init; const pointers have mutable vs const data distinctions—read declarations right-to-left.

    Example code

    const int c = 3;
  11. Question 11

    volatile?

    Prevents certain optimizations for memory-mapped hardware or signal handlers—misused for thread communication (wrong).

    Example code

    volatile int *mmio = (int *)0xDEADBEEF;
  12. Question 12

    static local variable?

    Single instance for function lifetime, initialized once—storage duration is program/static, not auto.

    Example code

    void f(void) { static int s = 0; s++; }
  13. Question 13

    static global/function?

    Internal linkage—symbol not visible to other translation units.

    Example code

    static void helper(void) {}
  14. Question 14

    extern?

    Declares symbol defined elsewhere—linker resolves across object files.

    Example code

    extern int g;
  15. Question 15

    What is a translation unit?

    A preprocessed source file compiled to one .o—one compilation unit.

    Example code

    // one .c file = one translation unit
  16. Question 16

    Header files?

    Declarations shared via #include; include guards or #pragma once prevent redefinition.

    Example code

    #ifndef H_H
    #define H_H
    void h(void);
    #endif
  17. Question 17

    What does static inline mean?

    inline suggests inlining; static gives internal linkage—common pattern for header-defined helpers in C.

    Example code

    static inline int add(int a, int b) { return a + b; }
  18. Question 18

    struct memory layout?

    Padding inserted for alignment; offsetof and #pragma pack affect layout—ABI sensitive across compilers.

    Example code

    struct S { char c; int i; }; // padding
  19. Question 19

    union?

    Overlapping members share storage—size is max member; type punning has strict aliasing rules.

    Example code

    union U { int i; float f; };
  20. Question 20

    enum in C?

    Integer constants; underlying type implementation-defined until C99 improvements—don't assume size without checks.

    Example code

    enum E { A, B };
  21. Question 21

    typedef?

    Creates aliases for types—readability for structs and function pointers.

    Example code

    typedef struct Node Node;
  22. Question 22

    Function pointers?

    Callbacks and vtable-like patterns; syntax is verbose—typedef helps.

    Example code

    int (*cmp)(const void *, const void *);
  23. Question 23

    qsort and bsearch?

    Library binary search and quicksort with comparator void*—must return negative/zero/positive consistently.

    Example code

    qsort(a, n, sizeof *a, cmp);
  24. Question 24

    strlen strcpy strcat dangers?

    Unbounded string functions risk overflows; prefer strncpy strncat with care or safer abstractions.

    Example code

    char buf[4]; snprintf(buf, sizeof buf, "%d", 123);
  25. Question 25

    snprintf?

    Bounded formatting into buffer; returns what would have been written—check truncation.

    Example code

    unsigned u = UINT_MAX; u++; // wraps
  26. Question 26

    What is integer overflow?

    Signed overflow is UB in C; unsigned wraps defined—use safe math libraries for security code.

    Example code

    unsigned char u = 255; int x = u; // promoted
  27. Question 27

    Integer promotion?

    Smaller ints promote to int in expressions—surprising results mixing signed/unsigned.

    Example code

    if (a & 1) {}
  28. Question 28

    Bitwise vs logical operators?

    & vs &&, | vs ||—mixing up causes subtle bugs and sometimes UB with side effects.

    Example code

    char bytes[4]; memcpy(bytes, &x, sizeof x);
  29. Question 29

    What is strict aliasing?

    Accessing an object through incompatible type is UB—char* is special exception for byte access.

    Example code

    void foo(int *restrict a, int *restrict b);
  30. Question 30

    restrict keyword?

    Promises no other pointer aliases the same object—enables optimizations; lying is UB.

    Example code

    printf("%d", va_arg(ap, int));
  31. Question 31

    Variadic functions?

    va_list, va_start, va_arg, va_end—caller/callee must agree on types; easy to corrupt stack if wrong.

    Example code

    #include <signal.h>
    void h(int s) {}
  32. Question 32

    setjmp/longjmp?

    Non-local jumps bypass stack unwinding—dangerous with modern invariants; avoid in C++ mixed code.

    Example code

    if (fopen("f", "r") == NULL) perror("open");
  33. Question 33

    Signals?

    Async handlers limited to async-signal-safe functions; prefer masking and polling self-pipe pattern.

    Example code

    printf("> "); fflush(stdout);
  34. Question 34

    errno?

    Thread-local error indicator for library calls—must save before other calls if needed.

    Example code

    int c = getchar(); if (c == EOF) {}
  35. Question 35

    FILE* and buffering?

    stdout line-buffered when tty; fflush after prompts; setvbuf controls policy.

    Example code

    #define MAX(a,b) ((a)>(b)?(a):(b))
  36. Question 36

    What is EOF?

    Macro int negative value distinct from valid unsigned char stream values—store in int not char when reading.

    Example code

    #if defined(__linux__)
    #endif
  37. Question 37

    Preprocessor macros?

    Text substitution—parenthesize parameters; prefer const/inline enums when possible.

    Example code

    static int x; // internal linkage
  38. Question 38

    #ifdef vs #if?

    ifdef tests defined symbol; if evaluates expressions—use for feature tests carefully.

    Example code

    #include <errno.h>
    if (remove("ghost.txt") != 0) perror("remove");
  39. Question 39

    What is linkage?

    External (default globals), internal (static), none (automatic locals)—affects symbol visibility to linker.

    Example code

    FILE *fp = fopen("data.txt", "r");
    if (fp) { setvbuf(fp, NULL, _IONBF, 0); fclose(fp); }
  40. Question 40

    const correctness?

    Pointers to const document read-only views—helps APIs communicate mutation intent.

    Example code

    void print(const int *p);
  41. Question 41

    What is Flexible array member (C)?

    Last struct member [] without size—alloc struct+extra bytes; C99 feature for variable-length tail storage.

    Example code

    struct H { size_t n; int d[]; };
    // malloc(sizeof(struct H) + n*sizeof(int))
  42. Question 42

    What is Compound literals (C)?

    Temporary objects (C99) with lifetime scope rules—useful for small structs passed by value.

    Example code

    int *p = (int[]){1,2,3};
  43. Question 43

    What is Designated initializers (C)?

    struct s = { .x = 1 }—clearer and order-independent initialization.

    Example code

    struct S s = { .x = 1, .y = 2 };
  44. Question 44

    What is Anonymous struct/union (C)?

    C11 allows unnamed members for ergonomic overlays in embedded structs.

    Example code

    struct { int a; int b; } s;
  45. Question 45

    What is _Alignas/_Alignof (C)?

    Control and query alignment requirements for SIMD or hardware structs.

    Example code

    _Alignas(16) char buf[64];
    printf("%zu", _Alignof(int));
  46. Question 46

    What is _Static_assert (C)?

    Compile-time assertions—catch broken assumptions early.

    Example code

    _Static_assert(sizeof(int) >= 4, "int too small");
  47. Question 47

    What is Thread support C11 (C)?

    threads.h optional; real code often uses pthreads on POSIX for portability.

    Example code

    // thrd_create / or use pthreads
  48. Question 48

    What is pthreads (C)?

    POSIX threads: mutex, cond, join—pair every create with join or detach to avoid leaks.

    Example code

    pthread_t t;
    pthread_create(&t, NULL, start, NULL);
    pthread_join(t, NULL);
  49. Question 49

    What is mutex types (C)?

    Normal, recursive, error-check—choose per deadlock risk; avoid locking order cycles.

    Example code

    pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_lock(&m);
  50. Question 50

    What is condition variables (C)?

    Always wait in a loop checking predicate—spurious wakeups are allowed.

    Example code

    pthread_cond_wait(&c, &m);
  51. Question 51

    What is atomic stdatomic.h (C)?

    Lock-free atomics in C11 where supported—use for counters and flags, not complex invariants alone.

    Example code

    _Atomic int x;
    atomic_store(&x, 1);
  52. Question 52

    What is memory order (C)?

    C11 atomics have memory_order seq_cst default; relaxed/acquire/release for performance experts only.

    Example code

    atomic_load_explicit(&x, memory_order_acquire);
  53. Question 53

    What is Compiler barriers (C)?

    Prevent reordering around critical sections—prefer proper atomics or mutexes.

    Example code

    // asm volatile("" ::: "memory");
  54. Question 54

    What is volatile and threads (C)?

    Does not synchronize threads—use atomics or mutexes; volatile is for hardware/signals.

    Example code

    // use atomics instead of volatile for sync
  55. Question 55

    What is ASan (C)?

    AddressSanitizer finds use-after-free, buffer overflows—compile and link with -fsanitize=address.

    Example code

    // gcc -fsanitize=address
  56. Question 56

    What is UBSan (C)?

    UndefinedBehaviorSanitizer catches shifts, signed overflow assumptions—great in CI debug builds.

    Example code

    // gcc -fsanitize=undefined
  57. Question 57

    What is MSan (C)?

    MemorySanitizer for uninitialized reads—slower, use selectively.

    Example code

    // clang -fsanitize=memory
  58. Question 58

    What is Valgrind (C)?

    memcheck for heap errors without recompile—heavy runtime cost.

    Example code

    // valgrind ./a.out
  59. Question 59

    What is DWARF debug info (C)?

    -g enables source-level debugging; split-dwarf reduces link memory.

    Example code

    // gcc -g
  60. Question 60

    What is strip symbols (C)?

    Smaller binaries; hide internals—keep unstripped builds for crash analysis.

    Example code

    // strip a.out
  61. Question 61

    What is static analysis (C)?

    clang-tidy, cppcheck catch many C bugs before runtime.

    Example code

    // cppcheck --enable=all .
  62. Question 62

    What is MISRA C (C)?

    Coding standard for safety-critical embedded—subset restricts risky constructs.

    Example code

    // follow MISRA rules in embedded
  63. Question 63

    What is Cert C (C)?

    Secure coding rules—focus on integer and string handling.

    Example code

    // CERT C secure patterns
  64. Question 64

    What is make (C)?

    Build dependencies; pattern rules; parallel -j—still common for small C projects.

    Example code

    all:
    	gcc -O2 -o app main.c
  65. Question 65

    What is CMake (C)?

    Meta-build generates Make/Ninja—cross-platform C/C++ standard.

    Example code

    cmake -S . -B build && cmake --build build
  66. Question 66

    What is Ninja (C)?

    Fast low-level build format—CMake can target it for quicker incremental builds.

    Example code

    ninja -C build
  67. Question 67

    What is pkg (C)?

    pkg-config supplies cflags/libs for dependencies—integrate in build scripts.

    Example code

    pkg-config --cflags --libs libpng
  68. Question 68

    What is shared libraries (C)?

    SONAME versioning; rpath/runpath; dlopen for plugins—ABI breaks require bump.

    Example code

    gcc -shared -fPIC -o libx.so x.c
  69. Question 69

    What is PIC code (C)?

    Position-independent code for shared objects—small overhead on some architectures.

    Example code

    gcc -fPIC -c x.c
  70. Question 70

    What is weak symbols (C)?

    Allow default implementations overridable at link time—used in libc hooks.

    Example code

    __attribute__((weak)) void hook(void) {}
  71. Question 71

    What is linker scripts (C)?

    Control section placement for embedded targets—VMA/LMA for flash vs RAM.

    Example code

    // MEMORY { FLASH : ORIGIN = 0x08000000, LENGTH = 512K }
  72. Question 72

    What is volatile MMIO (C)?

    Memory-mapped I/O registers need volatile accesses—ordering may need barriers.

    Example code

    *(volatile uint32_t *)0x40000000 = 1;
  73. Question 73

    What is DMA coherence (C)?

    CPU cache vs device visibility—flush/invalidate on architectures that need it.

    Example code

    // cache clean/invalidate before DMA
  74. Question 74

    What is endianness (C)?

    Network byte order htons/ntohs; file formats document endian—don't assume host order.

    Example code

    uint32_t h = htonl(0x01020304);
  75. Question 75

    What is unaligned access (C)?

    May trap or be slow on some CPUs—use memcpy for portable packed structs.

    Example code

    uint8_t b[4]; memcpy(&v, b, 4);
  76. Question 76

    What is bit fields (C)?

    Implementation-defined layout—avoid for portable wire formats; use masks explicitly.

    Example code

    struct { unsigned a:3; unsigned b:5; } f;
  77. Question 77

    What is const char* string literals (C)?

    Stored in read-only memory—modifying is UB; type should be const char*.

    Example code

    const char *s = "read-only";
  78. Question 78

    What is main signatures (C)?

    int main(void) or int main(int argc, char** argv)—return 0 or EXIT_SUCCESS.

    Example code

    int main(int argc, char **argv) { return 0; }
  79. Question 79

    What is getenv (C)?

    Environment variables not thread-safe on some platforms if modified—treat as read-only after startup.

    Example code

    const char *h = getenv("HOME");
  80. Question 80

    What is strtok (C)?

    Not reentrant—use strtok_r with saved state in threaded code.

    Example code

    char *tok = strtok_r(line, " ", &save);
  81. Question 81

    What is readdir (C)?

    Directory iteration not necessarily thread-safe per DIR*—one DIR per thread.

    Example code

    struct dirent *e;
    while ((e = readdir(d)) != NULL) {}
  82. Question 82

    What is fork (C)?

    Copy-on-write process split; careful with threads—only async-signal-safe between fork and exec.

    Example code

    pid_t p = fork();
    if (p == 0) { /* child */ }
  83. Question 83

    What is exec (C)?

    Replace process image; file descriptors may need FD_CLOEXEC discipline.

    Example code

    execl("/bin/ls", "ls", NULL);
  84. Question 84

    What is mmap (C)?

    Map files or anonymous memory; MAP_SHARED for IPC; msync for persistence guarantees.

    Example code

    void *p = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
  85. Question 85

    What is pipe and socketpair (C)?

    IPC between processes or threads—nonblocking and event loops integrate with select/poll/epoll.

    Example code

    int fd[2]; pipe(fd);
  86. Question 86

    What is poll (C)?

    Wait on fds with millisecond timeout—edge vs level triggered epoll nuances on Linux servers.

    Example code

    struct pollfd fds[1] = {{.fd=0,.events=POLLIN}};
    poll(fds, 1, 1000);
  87. Question 87

    What is ioctl abuse (C)?

    Driver-specific operations—documented per device; errors easy to mishandle.

    Example code

    ioctl(fd, REQUEST, &arg);
  88. Question 88

    What is errno thread safety (C)?

    POSIX makes errno thread-local—correct on modern libc for threaded servers.

    Example code

    // errno is thread-local on POSIX
  89. Question 89

    What is alloca (C)?

    Stack allocation dynamic—risk stack overflow; VLA similar cautions in C99.

    Example code

    int *p = alloca(n * sizeof *p);
  90. Question 90

    What is VLAs (C)?

    Variable length arrays on stack—optional in C11; disabled on some embedded compilers.

    Example code

    int a[n]; // if compiler supports VLA
  91. Question 91

    What is restrict and memcpy (C)?

    memcpy dst/src restrict expectation—memmove handles overlap correctly.

    Example code

    memcpy(dst, src, n); // no overlap
  92. Question 92

    What is bcopy (C)?

    Legacy BSD; memmove is standard portable overlap-safe copy.

    Example code

    memmove(dst, src, n); // overlap-safe
  93. Question 93

    What is endian memcpy (C)?

    Serialize integers portably by shifting bytes explicitly—don't cast struct pointers to char* for wire format without care.

    Example code

    uint32_t v; uint8_t b[4] = {0,0,0,1}; memcpy(&v,b,4);
  94. Question 94

    What is CRC (C)?

    Error detection on packets—table-driven implementations common in embedded.

    Example code

    // uint16_t crc = crc16_table[...]
  95. Question 95

    What is Fixed-point math (C)?

    Scaled integers on MCUs without FPU—careful with overflow and rounding.

    Example code

    int32_t q = (a * b) >> 8;
  96. Question 96

    What is Watchdog timers (C)?

    Pet in main loop or task scheduler—false trips vs hung detection tradeoff.

    Example code

    // IWDG->KR = 0xAAAA;
  97. Question 97

    What is Bootloader updates (C)?

    Dual-bank flash, checksum verify, rollback—state machine testing critical.

    Example code

    // verify CRC before swap banks
  98. Question 98

    What is Const data in flash (C)?

    Linker sections .rodata—verify const actually lands in ROM on embedded link scripts.

    Example code

    const uint8_t rom[] __attribute__((section(".rodata")));
  99. Question 99

    What is Stack usage analysis (C)?

    Worst-case stack depth tools for embedded—interrupt nesting counts.

    Example code

    // gcc -fstack-usage
  100. Question 100

    What is ISR rules (C)?

    Keep short; defer work; volatile flags—no malloc, limited printf.

    Example code

    void ISR_Handler(void) { flag = 1; }
  101. Question 101

    What is CMSIS (C)?

    ARM Cortex abstraction for vendors—standard register names and startup.

    Example code

    // NVIC_EnableIRQ(IRQn);
  102. Question 102

    What is HAL (C)?

    Vendor hardware abstraction—trade portability vs overhead vs direct registers.

    Example code

    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);