C programming interviews should test whether candidates can explain the relationship between types, object lifetimes, storage and the interfaces their code exposes. A strong candidate can distinguish what the language guarantees from behavior that happens to work on one compiler or machine.
These 120 C programming interview questions focus on portable hosted C, memory ownership, standard-library I/O, compiler and linker behavior, concurrency, ABI and debugging. The code examples use broadly supported C, and questions identify where C23 or implementation support matters. This is separate from hardware-specific Embedded C.
How can you tell whether a candidate understands the C code they just wrote?
Ask what happens when a multiplication exceeds size_t, a buffer is resized or a caller owns a pointer longer than intended. Look for an explicit invariant and a small test that can break the assumption. In remote interviews, Sherlock AI can help reviewers examine evidence of possible AI-assisted cheating, deepfakes, impersonation or other unauthorized assistance alongside that technical reasoning.
C Programming Interview Questions
Choose questions based on whether the position writes individual functions, maintains native libraries or owns production correctness and portability.
C Programming Interview Questions for Beginners
Start with translation, types, arrays, strings and basic memory management.
What is C used for?
What are the main stages of building a C program?
What is a translation unit in C?
What is a C header file for?
What is the difference between declaration and definition in C?
What is a function prototype?
What does main return in a hosted C program?
What is the difference between argc and argv?
What is an integer type in C?
How do signed and unsigned arithmetic differ?
What does sizeof return?
What is size_t used for?
What is a C pointer?
What is a null pointer?
What do the address-of and indirection operators do?
How are arrays and pointers different in C?
How are C strings represented?
What is the difference between strlen and sizeof?
Does C pass arguments by value or reference?
What is a struct in C?
What is a union in C?
What is an enum in C?
What does typedef do in C?
What is scope in C?
What is storage duration?
What does static mean in C?
What does extern mean in C?
What does const mean for a C object?
How is volatile different from const?
What is malloc in C?
What is the difference between malloc and calloc?
What does free do?
What is a memory leak?
What is a dangling pointer?
How do printf and fprintf differ?
How do you open and close a file in C?
What is a preprocessor macro?
What are include guards?
What is undefined behavior in C?
Which compiler warnings are useful for learning C?
C Programming Interview Questions for Intermediate
Move into conversions, allocation, I/O, alignment, functions and diagnostics.
How does pointer arithmetic work in C arrays?
When can you subtract two pointers in C?
What is integer promotion in C?
What are the usual arithmetic conversions?
How do you safely convert an integer to a smaller C type?
How do you prevent overflow in a C allocation size calculation?
How do you use realloc without losing the original allocation?
How do you distinguish ownership from borrowing in C?
How do you design a function that returns allocated memory?
How do you write C cleanup paths that release every resource?
What is the difference between memcpy and memmove?
How do you check that snprintf output fits a buffer?
Why is strncpy not a universal safe replacement for strcpy?
How do you read lines safely with fgets?
What is the difference between feof and ferror?
How should you handle partial reads or writes in C?
How do you parse an integer from text robustly?
What is errno and when should it be inspected?
What is the difference between an array of pointers and a pointer to an array?
How do multidimensional arrays work in C?
What is a variable-length array?
What are C function pointers used for?
What makes a qsort comparator correct?
How does inline differ from a macro?
What is alignment in C?
Why can C structs contain padding?
Why is memcmp unreliable as a general struct equality test?
How do you write portable code for endianness?
How do bit shifting rules affect portable C?
How should you check integer arithmetic before performing it?
What does restrict communicate to a C compiler?
What is the difference between a data race and a normal race condition?
When should you use a mutex instead of atomics?
What is atomicity versus memory ordering?
What is a C compiler sanitizer?
What is the role of debug symbols in C?
How do static and shared libraries differ?
What usually causes an undefined reference at link time?
How should C unit tests handle allocation failures?
How do you test a C API across compilers and platforms?
C Programming Interview Questions for Experienced
Assess deeper judgment about language guarantees, native APIs, concurrency, and production maintenance.
How do you audit a C API for unclear ownership?
How do you design an opaque C handle?
How would you design an API for caller-supplied buffers?
How do you manage memory across a shared-library boundary?
What is effective type and why does it matter?
What is strict aliasing in practical C reviews?
How do character types relate to object representation?
How do you avoid lifetime bugs with pointers into growable containers?
How do you handle a cache of pointers to changing memory?
What is an arena allocator and when is it useful?
How would you choose between copying data and borrowing pointers?
How do you design a C buffer type with clear invariants?
How would you implement a robust binary file parser in C?
How do you preserve ABI compatibility when evolving a C library?
What is the difference between API compatibility and ABI compatibility?
How do you use static assertions in C interfaces?
How would you investigate a failure that appears only at higher optimization?
How do you distinguish undefined, unspecified and implementation-defined behavior?
Why should C code avoid side effects that depend on argument evaluation order?
How do unsigned wraparound bugs differ from signed-overflow bugs?
How do you make a C cleanup path reliable under several failures?
How would you diagnose a steadily growing C process?
What can AddressSanitizer detect and what can it miss?
How does ThreadSanitizer differ from AddressSanitizer?
How would you reproduce a rare C data race?
How do release and acquire operations publish data in C?
When are relaxed atomics appropriate?
How would you evaluate a proposed lock-free C data structure?
What is false sharing in concurrent C programs?
How would you profile a slow C application?
When does a smaller C struct improve application performance?
What is the difference between structure-of-arrays and array-of-structures?
How would you use fuzz testing for a C parser defensively?
What is a good C code review checklist for memory safety?
How do you make diagnostic output reliable for portable C code?
What should an interviewee know about adopting C23 features?
How would you modernize an old C codebase without destabilizing it?
How do you choose which C checks to run in continuous integration?
How would you explain trade-offs when choosing C for a new component?
What interview exercise tests senior C judgment?
C Programming Interview Questions and Answers
Each answer describes what C or the implementation provides, then connects it to practical code review, testing or debugging.
C Programming Interview Questions and Answers for Beginners
Review the language building blocks using common compiler and library scenarios.
1. What is C used for?
C is a general-purpose compiled language with direct control over object representation, memory and calling interfaces. It is often used for native libraries, operating systems, language runtimes and performance-sensitive components.
A graphics library can expose a stable C-compatible API to callers in several languages. The project must explicitly manage resource ownership and platform assumptions; low-level control does not make code portable by itself.
2. What are the main stages of building a C program?
A typical toolchain preprocesses source, compiles it, assembles object code and links the resulting objects and libraries. Tools can combine these stages, but the distinction helps diagnose failures.
A missing header commonly fails during preprocessing or compilation, while a declared function without a linked definition can fail at link time. Use the actual diagnostic and build command to investigate the correct stage.
3. What is a translation unit in C?
A translation unit is source after inclusion and preprocessing as defined by the implementation’s translation process. Independently translated source files communicate through declarations and linkage conventions.
Including one header in two C files does not make them one translation unit. Definitions placed in a header can therefore appear multiple times at link time unless their linkage and definition rules permit it.
4. What is a C header file for?
A header normally publishes declarations, types and macros that callers need to compile against an interface. It should be self-contained where practical and avoid introducing unwanted public definitions.
A math interface may declare a function symbol and its parameter types while the implementation stays in one source file. Callers can include the header to receive consistent compiler type checking.
5. What is the difference between declaration and definition in C?
A declaration introduces information about an identifier and its type. A definition supplies the object or function definition as required by C’s rules; many definitions are also declarations, but not all declarations define storage.
An extern declaration can tell callers about a variable defined in another file. If the build omits the defining file, the source can compile and still fail to link.
6. What is a function prototype?
A prototype declares the parameter types of a function and enables call-site checking. Use an explicit void parameter list for a no-argument function when targeting dialects where an empty declaration has older semantics.
Putting the prototype in a shared header helps prevent a caller from passing an incompatible value. Compile the implementation against its own header so a mismatched declaration is detected early.
7. What does main return in a hosted C program?
Common standard hosted forms return int, with no arguments or with argc and argv. Returning zero indicates successful termination; use standard exit constants where readability or a nonzero failure status matters.
A command-line tool can return EXIT_FAILURE when opening its input fails. Use stderr for diagnostics and reserve stdout for normal output when the tool will be composed into a pipeline.
8. What is the difference between argc and argv?
argc counts the supplied argument entries and argv points to the argument strings, with a null sentinel after the last entry. Check the count before indexing a user argument.
When a tool requires a path, do not access argv[1] until you know it exists. The argument remains untrusted data and should be parsed or validated for the operation it controls.
9. What is an integer type in C?
C provides signed and unsigned integer types with specified ranges and relationships, but many exact sizes depend on the implementation. Choose a type that fits the domain and the interfaces you use.
Use size_t for object sizes and array indexes when appropriate. For a binary format requiring exactly 32 bits, use a suitable fixed-width type where available and explicitly handle encoding.
10. How do signed and unsigned arithmetic differ?
Unsigned arithmetic is defined modulo the range of its type after the relevant promotions and conversions. Ordinary signed overflow is undefined, not guaranteed wraparound.
Adding one to an unsigned value at its maximum can produce zero. A signed counter should check the boundary before adding rather than depend on one test build’s apparent behavior.
11. What does sizeof return?
sizeof returns a size in C bytes as size_t. A C byte is the size of char and has CHAR_BIT bits, which need not be assumed to equal eight on every implementation.
Use sizeof *ptr to allocate storage for the pointed-to type even if that type later changes. sizeof a pointer is not the size of the allocation or array it points to.
12. What is size_t used for?
size_t is the unsigned integer type used for object sizes and the result of sizeof. It is appropriate for many counts, but still requires attention to zero, overflow and conversion from signed or wider values.
A loop over length should not test whether an unsigned index is negative. Guard subtraction and allocation multiplication explicitly when a size is derived from external values.
13. What is a C pointer?
A pointer is a typed value that can designate an object or function, or have another allowed state such as a null value. Its valid use depends on lifetime, type and the bounds of the designated storage.
A pointer to an array element can be passed to a function together with a length. The address alone does not tell that function how many elements it may safely access.
14. What is a null pointer?
A null pointer is guaranteed not to designate any object or function. Test it before operations that require a valid target; do not assume a specific byte representation on every implementation.
malloc can return a null pointer on failure for a nonzero request. The caller should handle the failure before dereferencing it rather than relying on a crash as normal control flow.
15. What do the address-of and indirection operators do?
The unary address-of operator obtains a pointer to an eligible object or function. Indirection through a valid object pointer designates the pointed-to object, subject to type and lifetime constraints.
Taking the address of a local counter allows a function to update it through a pointer during that lifetime. Passing an address does not extend the lifetime after the declaring block ends.
16. How are arrays and pointers different in C?
An array contains a fixed sequence of elements in its declared storage, while a pointer is a value that can designate an element. Array expressions convert to a pointer in many contexts, but not every context.
sizeof an array declared in the current scope can yield the whole storage size. Once a function receives a pointer parameter, use an explicit length rather than expecting sizeof to recover the original array size.
17. How are C strings represented?
A C string is a character sequence terminated by a null character. A character array can contain bytes without being a string if no terminator appears within the accessible bound.
A buffer containing exactly four data bytes is not necessarily safe to print with a string conversion. Track its length or explicitly reserve and write a fifth byte for the terminator.
18. What is the difference between strlen and sizeof?
strlen scans a valid null-terminated string to count characters before its first null. sizeof reports the storage size of an expression’s type and usually does not inspect the contents.
For a 32-byte array initialized to the string cat, strlen is three and sizeof the array is 32. If the array is accessed through a pointer, sizeof reports the pointer size instead.
19. Does C pass arguments by value or reference?
C passes arguments by value. A pointer argument is itself copied, but the function can use that copy to modify an object the caller made accessible.
A swap function accepts pointers to two integers and writes through them. Reassigning one pointer inside the function does not change the caller’s pointer variable unless its address was passed too.
20. What is a struct in C?
A struct groups named members into one object, with member types and storage layout governed by the language and implementation. Padding can exist between members and at the end.
A point struct can hold x and y values. Compare members or serialize them explicitly rather than assuming the struct’s memory bytes are a portable file format.
21. What is a union in C?
A union provides overlapping storage for its members, with room and alignment sufficient for its declared members. A separate discriminator is often useful to indicate which representation an application should interpret.
A token can use an enum to distinguish a number from a name stored in a union. Keep the tag consistent with writes; do not infer the active representation from arbitrary overlapping bytes.
22. What is an enum in C?
An enum defines named integer constants and an enumerated type, with representation details that depend on the C version and implementation. It improves readability for a bounded application domain.
Use names such as STATUS_READY rather than unexplained integers. When reading untrusted stored data, still validate that the parsed number corresponds to a state your application recognizes.
23. What does typedef do in C?
A typedef adds another name for an existing type, not a distinct runtime representation or inherently incompatible type. It is useful for naming domain values and simplifying declarations.
A type alias for a coordinate can clarify intent. If different units must not mix, a plain typedef will not force the compiler to distinguish them; a wrapper struct can better express that boundary.
24. What is scope in C?
Scope determines where a particular declaration’s name is visible in source. It is distinct from storage duration, which determines the lifetime of an object, and linkage, which connects declarations.
A block-local variable may hide a name from an outer scope. Adding static changes its storage duration in common block-local use, but does not make the name visible outside the block.
25. What is storage duration?
It describes how long storage for an object is retained: common categories are automatic, static, thread and allocated storage duration. The category does not guarantee that a particular physical memory region is used.
A local automatic array normally ceases to be usable when its block ends. A static local retains its state across calls, which can introduce shared-state concerns that automatic storage avoided.
26. What does static mean in C?
At file scope, static can give an identifier internal linkage. On a block-scope object, it commonly gives static storage duration while the identifier remains block-scoped.
A private helper can be static at file scope to avoid exporting its name. A static local counter persists between calls and may require synchronization if multiple threads access it.
27. What does extern mean in C?
extern can declare an object or function with linkage, usually so a caller can refer to a definition provided elsewhere. The exact meaning depends on declaration context and whether an initializer is present.
Put a shared object declaration in a header and its intended definition in one implementation file. Do not initialize the object in the header unless your design explicitly allows each inclusion’s effect.
28. What does const mean for a C object?
const constrains modification through the relevant qualified type. A pointer to const and a const pointer constrain different things, and const is not a promise that every other access path sees immutable data.
A function taking const char pointer should not modify text through that pointer. It can still advance its local pointer, while the caller must keep the underlying storage valid during the call.
29. How is volatile different from const?
volatile concerns accesses that can have externally observable behavior, while const qualifies modification. volatile does not make ordinary concurrent access atomic or establish inter-thread synchronization.
A platform may expose a memory-mapped register through a volatile-qualified access. For shared application state across threads, use language atomics or a mutex, not a volatile flag as a lock.
30. What is malloc in C?
malloc requests a block of allocated storage and returns a pointer or signals failure with a null pointer for a nonzero request. It does not initialize a usable object’s values for you.
Check the multiplication for an array size and the allocation result before use. Establish who owns the returned allocation and frees it so error paths do not leak it.
31. What is the difference between malloc and calloc?
malloc requests a byte size without zeroing the allocation. calloc requests a count and size and initializes the allocated bytes to zero; all-bits-zero is not a universal representation for every possible type value.
calloc is useful when zeroed byte storage matches the application’s requirements. Do not assume that it is a substitute for explicit initialization of every pointer or non-integer representation on all platforms.
32. What does free do?
free ends the allocation lifetime for a valid allocated pointer; passing a null pointer does nothing. After freeing an allocation, pointers that referred to it no longer provide valid access to its former objects.
Free a buffer once its owner is done using it. Setting the owner pointer to null may clarify its local state, but it does not fix aliases that still refer to the released allocation.
33. What is a memory leak?
A leak occurs when allocated resources are no longer needed but remain unreleased, often because the program lost ownership information. Unreleased memory can accumulate even if each missed allocation is small.
A parser that returns early on invalid input may forget to free its temporary array. Exercise failure paths, use an ownership convention and validate with appropriate diagnostics instead of checking only successful requests.
34. What is a dangling pointer?
It is an informal term for a pointer no longer usable for the object it once designated, commonly after free or end of scope. The remedy is correct lifetime and ownership, not simply checking for null.
Returning a pointer to a local automatic buffer leaves the caller without valid storage. Copy into caller-provided storage or allocate and document the returned ownership explicitly.
35. How do printf and fprintf differ?
printf writes formatted output to stdout; fprintf writes to the specified stream. Both require a format string and arguments that match the conversion specifiers and the calling rules.
Use fprintf with stderr for diagnostics. Pass user text as an argument to a fixed string conversion rather than treating that text as a format string.
36. How do you open and close a file in C?
Use fopen with an appropriate mode and check its result before reading or writing. Close the stream when ownership ends, and consider whether a close or flush error affects the promised result.
A program generating a report should check both the write result and final close where durability matters. A successful open does not guarantee the complete file was written or accepted by the operating system.
37. What is a preprocessor macro?
A macro performs replacement during preprocessing rather than behaving like an ordinary typed function. Function-like macros have evaluation and token-expansion rules that can surprise callers.
A macro that repeats its argument can evaluate a side-effecting expression twice. Prefer a typed function where possible and review macro arguments, parentheses and side effects when a macro is necessary.
38. What are include guards?
Include guards use conditional preprocessing to avoid processing the same header contents repeatedly in one translation unit. They do not solve duplicate external definitions across multiple translation units.
Guard a header containing a type definition so indirect includes remain safe. Put an ordinary external object definition in one source file rather than depending on a guard to apply across the whole build.
39. What is undefined behavior in C?
Undefined behavior means the standard imposes no requirements for that program execution condition. It is not a documented error signal or a promise that the same behavior will occur across compilers and builds.
An out-of-bounds access can appear to work in one debug run but fail after optimization. Remove the invalid access and test boundaries; do not infer language guarantees from a single observed output.
40. Which compiler warnings are useful for learning C?
Enable appropriate warning sets, choose a target language version and review diagnostic output rather than relying on defaults. Warnings can expose mismatched types and suspicious conversions, but a clean build does not prove correctness.
Compile a small program with warnings such as Wall, Wextra and appropriate pedantic checks in GCC or Clang. Combine that with tests and sanitizers selected for the actual failure risks.
C Programming Interview Questions and Answers for Intermediate
Review implementation techniques and the preconditions that keep them portable.
41. How does pointer arithmetic work in C arrays?
Adding an integer to a pointer advances by elements of its pointed-to type according to array bounds. The valid range includes a one-past position for appropriate comparisons, not an object that may be dereferenced.
A loop can compare its current pointer with the end sentinel. It must stop before reading the sentinel and should not compute pointers beyond that range even if it never intends to use them.
42. When can you subtract two pointers in C?
Pointer subtraction is defined for pointers into the same array or its one-past position, when the difference is representable in ptrdiff_t. Unrelated allocation addresses are not a portable distance calculation.
Subtract a range’s current element pointer from its array base to get an index. For independently allocated objects, track explicit identifiers or sizes rather than subtracting their addresses.
43. What is integer promotion in C?
Smaller integer types can be promoted before many arithmetic operations. Mixed-type conversions then determine the evaluation type, so operand declarations alone do not tell you how the expression behaves.
Adding two narrow unsigned values may first produce an int on a typical target. If the result is stored back in a narrow type, check whether narrowing meets the application’s intended range.
44. What are the usual arithmetic conversions?
They determine a common type for many arithmetic and comparison operations after applicable promotions. In signed and unsigned mixes, representable ranges and type ranks can make an operand convert unexpectedly.
A signed negative value compared against an unsigned size may become large under common conversions. Validate the sign first and then cast only after proving the destination can represent the value.
45. How do you safely convert an integer to a smaller C type?
Check source bounds against destination limits before conversion, taking signedness into account. Explicit casts communicate intent but do not themselves prevent loss of information.
Before converting a size_t to a signed int for a legacy API, reject values above INT_MAX. The cast should come after the guard, with an error path callers can handle.
46. How do you prevent overflow in a C allocation size calculation?
Check that multiplying count by element size fits size_t before evaluating the multiplication. Decide separately how zero elements should behave and handle allocation failure.
If element size is nonzero, count greater than SIZE_MAX divided by that size cannot be represented. Reject it rather than allocating a wrapped byte count that is smaller than the intended array.
47. How do you use realloc without losing the original allocation?
For a nonzero valid requested size, assign realloc’s result to a temporary pointer. If it fails, keep the original pointer; if it succeeds, use the returned pointer and treat old aliases as invalid.
A vector can grow only after validating capacity multiplication. Reassign the buffer and capacity after success, and define zero-size behavior independently instead of relying on realloc with zero.
48. How do you distinguish ownership from borrowing in C?
Ownership means responsibility for releasing or transferring a resource. A borrowed pointer permits limited use for a documented lifetime without granting that responsibility.
A getter may return a string owned by the containing object. Tell callers whether a subsequent mutation invalidates the borrow and provide a copying API if callers need independent lifetime.
49. How do you design a function that returns allocated memory?
Document whether the caller owns the result, what allocator or release function to use, and how an error is represented. Initialize output parameters predictably and do not leave partially initialized results on failure.
A library might return a status and store a buffer only on success. A paired destroy function gives the library control over the allocation strategy, which is useful across module boundaries.
50. How do you write C cleanup paths that release every resource?
Give acquired resources explicit owners and arrange cleanup in a predictable order. A single cleanup block is often suitable when a function acquires several resources and any step can fail.
If a file opens and the second allocation fails, cleanup still closes the file. Initialize optional resources to safe states and run tests that force each acquisition to fail independently.
51. What is the difference between memcpy and memmove?
memcpy copies bytes when its source and destination ranges do not overlap. memmove handles overlap according to its contract. Both still require valid ranges of the specified size.
Shifting records within a buffer can overlap, so use memmove. For transferring bytes between separate verified buffers, memcpy communicates the stronger precondition that optimization can rely on.
52. How do you check that snprintf output fits a buffer?
A negative result signals a formatting error. A nonnegative result reports the characters that would have been written, excluding the terminator; a result at least the capacity means it did not fit.
A log label formatted into a fixed array should check truncation instead of treating any nonnegative return as full success. Validate a negative value before converting it to size_t.
53. Why is strncpy not a universal safe replacement for strcpy?
strncpy can fill the remaining destination with zeros and may not append a terminator if the source is too long. Its fixed-width semantics are not the same as every application’s intended bounded string copy.
For a user-visible label, use a length-aware contract and verify fit or explicitly handle truncation. Do not later call strlen on a destination that might lack a terminator.
54. How do you read lines safely with fgets?
Supply the array capacity as required by the API, check its return, and account for whether the newline fit. EOF, a read error and an overlong input line can require different responses.
A configuration parser can reject a partial line instead of treating the continuation as a second record. If binary NULs are possible, a line-oriented string function may not suit the format.
55. What is the difference between feof and ferror?
feof reports that the stream’s end-of-file indicator is set; ferror reports its error indicator. Check the actual read result first and then use the indicators to distinguish why input stopped.
A loop should process only successfully read values, not use while not EOF as a predictor of the next read. That common mistake can process stale data one extra time.
56. How should you handle partial reads or writes in C?
Interpret the number of elements or bytes actually transferred and consult the interface contract. Use a bounded loop where appropriate, and distinguish clean end, transient conditions and permanent errors.
A fixed-size binary header reader should reject a truncated file rather than decode unused bytes. On output, verify the full intended payload or report a precise failure upstream.
57. How do you parse an integer from text robustly?
Use a conversion function such as strtol with an end pointer, check range indicators and validate converted bounds for the destination type. Decide whether whitespace and trailing characters are allowed.
The string 12ms is not a pure integer merely because a conversion yields 12. If the contract says digits only, enforce that format and check that conversion consumed the intended entire input.
58. What is errno and when should it be inspected?
errno is set by certain library operations under documented conditions. Check the primary return value or documented status first; successful calls need not clear a previously stored errno.
Before a strtol conversion, initialize errno if the contract requires checking range errors afterward. Do not treat a nonzero errno from unrelated earlier work as proof that a successful call failed.
59. What is the difference between an array of pointers and a pointer to an array?
An array of pointers stores several pointer values; a pointer to an array designates an array object with a particular element type and bound in its type. Parentheses in declarations distinguish them.
An array of character pointers can hold separate strings. A pointer to a fixed-width character array is useful for a contiguous matrix whose row stride the compiler must know.
60. How do multidimensional arrays work in C?
A multidimensional array is an array of arrays, with inner arrays stored as the declared element type. Passing it to functions requires a compatible row type or another explicit layout contract.
A two-dimensional grid can be passed with a known column count, or represented as flat storage with explicit strides. A pointer to pointer does not automatically describe the same layout.
61. What is a variable-length array?
A variable-length array has a bound evaluated at execution in applicable contexts. Support and requirements vary by C version and implementation, and large runtime sizes need deliberate bounds.
A small validated automatic buffer may be acceptable for a target that supports the construct. For externally supplied or large sizes, consider an explicitly bounded allocation and handle failure.
62. What are C function pointers used for?
A function pointer designates a function with a compatible type and can be passed as a callback or stored in a table. The function signature is part of the contract.
A sort function can receive a comparison callback. Pass context through a supported interface or explicit object rather than depending on hidden global state when concurrency matters.
63. What makes a qsort comparator correct?
It must return a negative, zero or positive value according to a consistent ordering and match the required signature. Avoid computing differences that could overflow.
Compare two integers using relational results instead of subtracting them. Check tie-breaking when an ordering includes several properties, and do not assume qsort preserves order among equal entries.
64. How does inline differ from a macro?
An inline function still has normal types and function-call semantics, and it is not a guarantee of inlining. Macros substitute tokens and can evaluate argument expressions more than once.
For a typed small helper in a header, static inline often gives simple linkage behavior. Choose a macro only when preprocessing behavior or another constraint actually requires it.
65. What is alignment in C?
An object’s type may require addresses with a specific alignment. Casting a byte address to another pointer type does not create suitable alignment or make an unrelated object present there.
An input buffer read from a file can begin at an unaligned address. Decode through appropriately sized bytes or a suitable copy rather than dereferencing an assumed native struct pointer.
66. Why can C structs contain padding?
Implementations may insert padding to meet member and struct alignment requirements. The exact layout depends on the target, compiler and applicable ABI, not merely the sum of member sizes.
Reordering fields can change sizeof on one platform, but it does not establish a portable interchange format. Use explicit serialization and preserve published ABI layout deliberately.
67. Why is memcmp unreliable as a general struct equality test?
Bytes of padding and object representations may differ even when semantic members compare equal. Use member-wise equality or a canonical serialized representation where that is the actual comparison contract.
Two equal logical records can have different padding bytes after different initialization histories. Compare their IDs and fields, not arbitrary object bytes, unless you have a carefully defined byte contract.
68. How do you write portable code for endianness?
Define the byte order of external formats and explicitly encode or decode fixed-width fields. Do not rely on the machine’s native integer layout just because tests run on one architecture.
A file header can store big-endian length bytes and reconstruct them using bounded unsigned operations. Test with fixed fixtures whose contents are independent of host representation.
69. How do bit shifting rules affect portable C?
Use a valid nonnegative shift count less than the width of the promoted left operand and choose types suited to the needed operation. Signed values and promotions can change which cases are defined.
When assembling a 32-bit field, convert octets to an unsigned width before shifting and bound the shift. Avoid depending on a compiler’s typical arithmetic shift behavior for portable signed calculations.
70. How should you check integer arithmetic before performing it?
Compare operands against representable limits or use an appropriate checked-arithmetic facility supported by the target. Do not test a result after an operation whose overflow would already be undefined.
Before signed addition, consider both positive and negative bounds. For unsigned sizes, defined wraparound is still wrong if the result is intended to describe a valid capacity.
71. What does restrict communicate to a C compiler?
It provides aliasing-related promises about how objects are accessed through certain pointer expressions over their scope. Use it only when callers can uphold the contract; it does not check relationships at runtime.
A copy-like helper may allow more optimization if source and destination satisfy its documented constraints. If callers can overlap the ranges, choose a compatible interface instead of claiming restrict optimizes code safely in all cases.
72. What is the difference between a data race and a normal race condition?
A data race refers to conflicting unsynchronized accesses under the language memory model and can make C behavior undefined. Race condition is a broader term for logic whose correctness depends on interleaving.
Even atomically updating two fields can have a logical race if their combined invariant is not protected. Use the right synchronization for both language safety and business correctness.
73. When should you use a mutex instead of atomics?
Use a mutex when several operations or values form a compound invariant, or when lock-based logic is clearer. Atomics are appropriate for narrower protocols whose memory-order guarantees are understood.
Updating both queue head and size usually needs one coherent synchronization strategy. Atomic size alone will not make independent list pointer operations safe.
74. What is atomicity versus memory ordering?
Atomicity governs whether an operation on an atomic object is indivisible; ordering governs visibility relationships among operations in threads. An atomic operation does not automatically publish unrelated data under every memory order.
A relaxed counter can be useful for approximate statistics. Publishing a newly initialized object to another thread requires a separate synchronization argument, such as an appropriate release and acquire pair.
75. What is a C compiler sanitizer?
A sanitizer instruments a build to detect certain classes of runtime errors when executed. It provides useful diagnostics but does not prove the absence of errors on paths not tested or outside its detection scope.
An address sanitizer can expose an invalid access in a boundary test. Run representative workloads and maintain portable assumptions instead of making sanitizer success the only correctness evidence.
76. What is the role of debug symbols in C?
Debug symbols map executable behavior to source and types, making diagnostics and crash investigation easier. Optimization and missing artifacts can still limit what a debugger shows.
Keep symbols or equivalent symbol files for the exact released artifact under appropriate controls. Using symbols from a different build can point an investigation at misleading source lines.
77. How do static and shared libraries differ?
Static libraries provide object code incorporated by linking as appropriate. Shared libraries are resolved or loaded according to the platform’s runtime linkage model and can evolve separately under an ABI contract.
Static linking can simplify some deployments but increase artifact coupling or size. Shared libraries enable independent updates only if exported symbols and representations remain compatible.
78. What usually causes an undefined reference at link time?
The linker could not find a needed definition with the expected symbol identity in the selected objects and libraries. Investigate missing build inputs, linkage and toolchain-specific library order or options.
A header may declare processing_function correctly while its object file was omitted. Inspect the actual link invocation and symbols rather than adding a second conflicting definition.
79. How should C unit tests handle allocation failures?
Provide a controlled way to inject failures or isolate allocation behind a documented seam, and verify cleanup and returned state for each acquisition path. Do not allow tests to depend on unintentionally exhausting the host.
Force the second allocation in a parser to fail, then check that the first buffer is cleaned up and no partial output escapes. Repeat for success and empty input to cover ownership transitions.
80. How do you test a C API across compilers and platforms?
Choose representative compiler and target configurations, pin the language mode and validate both behavior and build diagnostics. Explicitly test data widths, byte order or runtime interfaces when the API depends on them.
A file parser can run the same byte fixtures on Linux and macOS and on different architectures where supported. Stop treating the developer’s default compiler output as a portable specification.
C Programming Interview Questions and Answers for Experienced
Review architecture and debugging decisions with practical verification examples.
81. How do you audit a C API for unclear ownership?
Trace each pointer or resource through acquisition, aliasing, transfer, mutation and release. Check both successful and failed calls and document what remains valid after each operation.
A buffer returned by a parser might be borrowed until the next parse, but a caller may store it longer. Add separate borrowed and owning interfaces or strengthen documentation and tests around invalidation.
82. How do you design an opaque C handle?
Expose an incomplete type with creation, use and destruction functions, and keep the layout private. Specify valid handle lifetime, thread-safety rules and which return values indicate failure.
An opaque connection type lets later versions add fields without forcing callers to rebuild around the struct size. It does not by itself make all operations legal concurrently; the API must promise that separately.
83. How would you design an API for caller-supplied buffers?
Specify the buffer and capacity, output size, ownership and behavior when capacity is insufficient. Define whether asking for required size without copying is supported, and account for changes between size inquiry and retrieval.
A serializer can return the required byte count or a clear short-buffer status. It should not silently produce a truncated value that callers interpret as a valid complete record.
84. How do you manage memory across a shared-library boundary?
Define whose allocator created the storage and how callers release it. Use paired allocation and destruction APIs where runtimes or allocators might differ, and preserve the compatibility contract across versions.
A widget library can return a handle only its destroy function frees. Do not assume allocation from one module is safely released through whatever heap a different module happens to use.
85. What is effective type and why does it matter?
C defines which lvalue types may access an object, with rules depending on storage and how values are established. Access through an incompatible type can violate assumptions used by optimization.
A byte sequence from a file is not automatically a native object matching a cast pointer. Decode into appropriately formed values or use a standards-compatible copy when the representation assumptions are justified.
86. What is strict aliasing in practical C reviews?
It is the compiler’s ordinary ability to rely on rules governing which differently typed accesses can designate the same object. Code that violates those rules can appear correct until optimization changes.
When reading object representation, suitable character types can inspect bytes. Reinterpreting an arbitrary object through an unrelated typed pointer needs a legitimate language rule, not just a matching size.
87. How do character types relate to object representation?
The language permits appropriate character-type access to inspect object bytes, subject to ordinary bounds and lifetime. This does not make arbitrary bytes meaningful as another type or create a portable serialized form.
Printing a local object’s bytes can aid diagnostics. For a file format, encode documented values explicitly and do not expose padding or assume byte order and representation match another architecture.
88. How do you avoid lifetime bugs with pointers into growable containers?
Treat growth, removal and destruction as explicit invalidation points. Prefer indices, stable handles or copies when callers need references that survive a resize, and rederive internal pointers after allocation changes.
A vector client can keep an index across append operations, but a pointer to an old element may be invalid after realloc. Recheck whether the index still identifies the intended element after insertion or deletion.
89. How do you handle a cache of pointers to changing memory?
Define the invalidation and lifetime strategy before caching: pin objects, use stable ownership, or cache keys and resolve them again. Access must remain safe across concurrent destruction or relocation.
A registry can resolve stable IDs under a lock and return a documented reference. Holding raw pointers to movable storage across an unrelated update is unsafe even if tests usually keep the same address.
90. What is an arena allocator and when is it useful?
An arena groups allocations with a shared lifetime so they can be reclaimed together. It can simplify temporary allocation but needs deliberate alignment, capacity and object ownership rules.
A request parser can allocate temporary objects in one arena freed at request completion. Do not return pointers from that arena to a cache or long-lived caller without copying or transferring suitable ownership.
91. How would you choose between copying data and borrowing pointers?
Compare lifetime complexity, performance, mutability and interface boundaries. Prefer copying at boundaries where data may outlive or change independently of the source, and measure before assuming copies dominate performance.
Borrowing short-lived input can make a parser efficient. When callers retain the parsed value after the request, make an owned copy or explicitly document and enforce the source lifetime.
92. How do you design a C buffer type with clear invariants?
Track pointer, used length and capacity with defined zero and ownership states. Validate capacity growth and maintain invariants after failures, rather than encoding them in undocumented caller assumptions.
A buffer can require used length no larger than capacity and forbid positive length with null data. Check those conditions in tests after repeated append, allocation failure and reset.
93. How would you implement a robust binary file parser in C?
Parse with explicit length tracking, bounded conversions and representation-aware decoding. Validate each field and derived size before access or allocation and keep incomplete state from escaping on failure.
A length field must fit both remaining bytes and application limits. Decode separately from native structs, use an owned output contract and test invalid, empty and truncated files with synthetic fixtures.
94. How do you preserve ABI compatibility when evolving a C library?
Retain established symbol signatures, calling conventions and exposed layouts, or version interfaces deliberately. Test against existing compiled clients as well as newly built source callers.
Adding a field can break clients allocating a public struct by its old size. Opaque handles or explicitly sized extension structures help when planned from the outset; they cannot retroactively change an existing contract unnoticed.
95. What is the difference between API compatibility and ABI compatibility?
API compatibility concerns whether source callers still build and behave as expected. ABI compatibility concerns whether previously built components can interact correctly using binary layouts, names and calling conventions.
A header edit may leave all new source calls compiling but change a struct layout used by old binaries. Test both dimensions if clients upgrade a shared library without rebuilding.
96. How do you use static assertions in C interfaces?
A static assertion detects a compile-time mismatch in an assumption expressible at compile time. Use it for stated platform requirements, not as a replacement for runtime validation of input data.
An integration can require a known type size for a local ABI and fail the build if unavailable. For external byte formats, a size assertion alone cannot prove host byte order or input validity.
97. How would you investigate a failure that appears only at higher optimization?
Compare compiler modes, minimal reproductions and diagnostics, with early attention to undefined behavior, uninitialized values and invalid aliasing or lifetime assumptions. Do not assume optimization is at fault.
Compile relevant tests with warnings and sanitizers, then check which invariants no longer hold. Keep the exact compiler options and verify a standards-compatible fix under multiple builds.
98. How do you distinguish undefined, unspecified and implementation-defined behavior?
Undefined behavior imposes no requirements for that condition. Unspecified behavior permits several choices without requiring a documented one, while implementation-defined behavior requires a documented choice by the implementation.
Choose code that works across valid choices unless a platform requirement is intentional. For a target-specific dependency, record it, test it and avoid presenting it as guaranteed by the language.
99. Why should C code avoid side effects that depend on argument evaluation order?
The evaluation order of function arguments is not generally specified, and unsequenced conflicting access can be undefined. Break expressions into statements whose ordering is explicit.
Compute an increment and a value read in a deliberate order before passing results to a function. Do not rely on the particular order printed by one compiler in a debug configuration.
100. How do unsigned wraparound bugs differ from signed-overflow bugs?
Unsigned operations can wrap according to defined rules, which can still violate capacity, loop or business invariants. Ordinary signed overflow is undefined and permits stronger compiler assumptions.
A wrapped byte count may be formally defined but too small for the expected allocation. Check both for representability rather than checking only whether the process crashed.
101. How do you make a C cleanup path reliable under several failures?
Track acquisition state explicitly and guarantee reverse or otherwise correct release ordering. Preserve the primary error and define whether cleanup errors affect the final result.
If writing output fails and closing also fails, report useful context without losing the first cause. Inject failures at every step and verify that future callers cannot see a half-built object.
102. How would you diagnose a steadily growing C process?
First separate live allocation growth, allocator retention and unrelated resource leaks. Compare representative snapshots or profiles and track which ownership paths fail to return to baseline.
A leak may occur only after an uncommon parse error. Test that path repeatedly with a fixed workload and verify retained allocations decline after the fix rather than relying only on process RSS.
103. What can AddressSanitizer detect and what can it miss?
It can detect many invalid memory accesses and lifetime errors in instrumented executions. It cannot cover unexecuted paths or every logical misuse, and availability and coverage depend on the runtime and target.
Run the relevant boundary and failure tests under the sanitizer. A missed bug can still exist in code paths that ordinary tests never reach or in logic that uses valid memory with an incorrect record ID.
104. How does ThreadSanitizer differ from AddressSanitizer?
ThreadSanitizer targets data races and related synchronization problems in suitable builds; AddressSanitizer targets many memory access errors. Select supported build configurations and test realistic concurrent schedules.
Use separate test runs when toolchains do not support combining these diagnostics. A clean thread run does not prove a custom lock-free protocol is logically correct under all possible interleavings.
105. How would you reproduce a rare C data race?
Preserve exact thread activity, use suitable instrumentation and vary schedule and load under a controlled test. Seek the conflicting accesses and missing synchronization rather than adding arbitrary delays as a fix.
Instrument a queue under repeated producers and consumers and correlate failing operations. Use deterministic test coordination where possible so the repaired invariant can be checked without relying on luck.
106. How do release and acquire operations publish data in C?
A release operation and an acquire operation that observes the appropriate value can create a synchronization relationship, allowing the receiving thread to see earlier writes under the memory model. The full protocol still matters.
One thread can initialize a payload and publish a flag with release, and another can read it after a matching acquire. Do not reuse or mutate the payload unsafely after publication.
107. When are relaxed atomics appropriate?
Use relaxed atomics when an indivisible update is required but it need not establish ordering for other data. Explain why stale or out-of-order observations are acceptable for the purpose.
A metrics-only counter can be updated and read with relaxed operations. If the counter becoming nonzero is used to indicate a pointer is ready, the design needs a proper publication mechanism.
108. How would you evaluate a proposed lock-free C data structure?
Check whether the correctness proof covers memory ordering, concurrent reclamation, progress and target support. Compare against a simple mutex design and measure the actual workload before accepting complexity.
A lock-free queue can still access objects that another thread freed if its reclamation design is flawed. Benchmark representative contention and use appropriate correctness analysis rather than relying on speed in one run.
109. What is false sharing in concurrent C programs?
False sharing can occur when independent frequently written data shares a hardware cache line, causing coherence traffic despite no logical shared value. It is a performance issue distinct from a language data race.
Measure per-thread counters before adding padding or alignment. A layout adjustment can improve throughput on one target but grow memory use or hurt other access patterns.
110. How would you profile a slow C application?
Measure representative workloads and identify wall-time, CPU, allocation and I/O bottlenecks with suitable tools. Start from a baseline, change one hypothesis and verify both performance and behavior.
A parser could be allocation-bound rather than computation-bound. Reuse temporary storage if profiling supports it, then compare worst-case inputs and memory footprint instead of optimizing a loop by intuition.
111. When does a smaller C struct improve application performance?
A smaller struct may improve memory locality or reduce bytes moved, particularly in large arrays. Benefits depend on access patterns and must be weighed against ABI, alignment and readability constraints.
Reordering private fields might increase useful records per cache line. Compare throughput under realistic access and avoid changing a public binary layout merely for a presumed local gain.
112. What is the difference between structure-of-arrays and array-of-structures?
An array of structures stores each record’s fields together, while a structure of arrays groups the same field across records. Choose according to which values calculations read together and how updates and APIs behave.
A vector loop over only x coordinates may benefit from contiguous x storage. Code processing full records together may find the other layout simpler; benchmark conversion costs too.
113. How would you use fuzz testing for a C parser defensively?
Run the parser in a controlled environment against varied synthetic inputs, with resource limits and diagnostics. Treat findings as defects to fix and minimize for regression tests, not as instructions for reproducing an attack against deployed targets.
Exercise malformed lengths, partial inputs and unexpected encodings before release. After a find, patch validation and add a bounded regression that proves safe failure with your owned parser.
114. What is a good C code review checklist for memory safety?
Check range computation, pointer validity, lifetimes, ownership, cleanup and synchronization. Verify externally provided values are validated before being used as sizes, format directives or indexes.
Review a parser for short and oversized input as well as valid records. Favor APIs with explicit lengths and deterministic failures so a later caller is less likely to depend on undocumented storage assumptions.
115. How do you make diagnostic output reliable for portable C code?
Use conversion specifiers matching types and keep fixed format strings for untrusted text. Check where buffers can truncate and ensure diagnostics communicate failure without relying on platform-specific widths.
Use the correct size_t format rather than guessing it is unsigned long. For fixed-width integers, use the appropriate standard formatting macro or explicitly cast to a type matching the chosen specifier.
116. What should an interviewee know about adopting C23 features?
Check compiler and library support separately, declare the project’s dialect and test fallback paths for supported targets. A feature specified by a standard is not necessarily available in a particular deployed toolchain.
Checked integer arithmetic can simplify portable bounds logic where the header is supported. On older targets, keep a tested explicit check rather than silently using another dialect’s behavior.
117. How would you modernize an old C codebase without destabilizing it?
Establish builds and tests across supported targets, then fix high-risk ownership and boundary patterns incrementally. Prefer small verified changes and preserve published source and binary interfaces where needed.
Wrap raw buffer operations behind an explicit invariant before rewriting every caller. Keep new warnings actionable and use targeted regression tests so improvements do not combine with unnecessary behavior changes.
118. How do you choose which C checks to run in continuous integration?
Mix warning-rich builds, unit and integration tests, representative targets and selected sanitizer or analysis jobs. Choose a quick feedback path and deeper checks that cover important risks without making failures impossible to debug.
A library might run core tests on each change and sanitizer configurations on a matrix. Clearly identify which artifact, options and input caused a failure so the next engineer can reproduce it.
119. How would you explain trade-offs when choosing C for a new component?
Weigh portability, latency and interface control against ownership complexity, maintenance and memory-safety requirements. Evaluate whether existing libraries or other languages meet the constraints with less ongoing risk.
A documented native extension may need a C ABI but can use another implementation internally. Identify the boundary that truly requires C rather than making the entire service inherit its risks.
120. What interview exercise tests senior C judgment?
Give the candidate a small API with ambiguous ownership, one constrained input and a portability failure. Ask them to state the invariants, propose a safe design and describe how tests would falsify assumptions.
A binary read function may return a pointer to temporary storage while trusting an input length. A strong answer separates validation, object representation and caller ownership, then adds focused success and failure tests.
C Programming Documentation and Further Reading
The WG14 draft describes language rules; compiler and library manuals document particular implementations. Check the compiler dialect, target and library versions that your project actually supports.
Similar Posts
