C interview questions and answers: pointers, memory and undefined behavior
C interview questions check whether you understand what the machine does with your code: pointers and arrays, pointer arithmetic, where memory lives, malloc and free, string handling without overflows, struct padding, const, volatile and static, and undefined behavior. Expect output-prediction snippets, short functions written by hand such as strlen, memmove or reversing a linked list, and for embedded roles, bit manipulation on registers. The strongest answers explain the memory picture, not just the syntax.
By Evin JohnPublished 11 min read
Where C programming interview questions come up
C is still the working language of firmware, operating systems, drivers, networking stacks, databases and many performance-sensitive libraries. Interviews for those jobs test C directly. Campus and fresher hiring in many countries also uses C as the first programming test, often as a written or online round of "what does this print" questions. For experienced candidates the questions shift toward memory ownership, debugging crashes and the corners of the language where code compiles cleanly and still misbehaves.
- Online test or written roundShort snippets with pointer tricks, operator precedence, macros and storage classes. You predict the output or spot the bug.
- Live coding in CImplement a string function, a linked list operation, a dynamic array or a ring buffer without library help. Edge cases and memory cleanup are graded as much as the main logic.
- Technical deep diveQuestions about your projects: how you managed memory, how you found a crash, why you chose a data layout. Embedded teams ask about registers, interrupts and timing.
- Behavioral roundDebugging stories and teamwork. A good C story usually involves a crash or corruption you tracked down with a tool and a hypothesis.
Pointers and arrays
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Is an array the same as a pointer? | Decay rules | No. An array is a block of elements with a fixed size. In most expressions its name converts to a pointer to the first element, but sizeof, & and string-literal initialization see the real array. |
Why does sizeof of an array parameter give 8? | Decay in parameters | A parameter declared int arr[] is really int *arr, so sizeof measures a pointer (8 bytes on a typical 64-bit build). Pass the length as a separate argument. |
Are a[i], *(a + i) and i[a] the same? | Subscript definition | Yes. Subscripting is defined as pointer addition plus dereference, and addition commutes. Mention that i[a] is a curiosity, not a style choice. |
What does p + 1 do if p is an int *? | Pointer arithmetic | It moves by sizeof(int) bytes. Arithmetic is scaled by the size of the pointed-to type, and it is only defined inside one array object or one past its end. |
int *p[10] versus int (*p)[10]? | Declarator reading | The first is an array of ten pointers. The second is one pointer to an array of ten ints, so p + 1 jumps the whole array. Read declarations from the name outward. |
| When do you need a pointer to a pointer? | Pass by value | When a function must change the caller's pointer, such as allocating a buffer or inserting at the head of a list. C passes everything by value, including pointers. |
| What is a dangling pointer? | Lifetime | A pointer to memory that is no longer valid: a freed block or a local variable whose function has returned. Setting a pointer to NULL after free helps but does not fix other copies. |
const int *p, int *const p, const int *const p? | Const placement | Pointer to const data, const pointer to mutable data, and both const. Read right to left from the name. |
What is a void * used for? | Generic memory | A pointer to any object type, used by malloc, memcpy and qsort. You cannot dereference it or do arithmetic on it in standard C without a cast. |
#include <stdio.h>
static size_t size_in_callee(int arr[]) {
return sizeof arr; /* arr is an int * here */
}
int main(void) {
int a[10] = {1, 2, 3, 4, 5};
printf("%zu %zu\n", sizeof a, size_in_callee(a));
int *p = a;
printf("%d %d %d\n", a[2], *(p + 2), 2[a]);
int (*whole)[10] = &a; /* pointer to the entire array */
printf("%td %td\n",
(char *)(p + 1) - (char *)p, /* one int */
(char *)(whole + 1) - (char *)whole); /* ten ints */
return 0;
}Memory layout, malloc and free
- Describe the memory layout of a C program. Code (text), initialized globals and statics (data), zero-initialized globals and statics (bss), the heap that grows with allocations, and the stack of function frames. Say that the exact layout is up to the platform, and that string literals usually sit in a read-only section.
- What is wrong with returning the address of a local variable? The local lives in the function's stack frame, which is gone after return. The pointer dangles and reading it is undefined behavior. Return by value, use a caller-provided buffer, or allocate.
- malloc versus calloc versus realloc? malloc gives uninitialized memory, calloc zeroes it (and common implementations check the count times size multiplication for overflow), realloc resizes and may move the block. All return NULL on failure.
- What happens if you free the same pointer twice? Undefined behavior. Allocators often corrupt their bookkeeping, and the crash shows up later somewhere unrelated, which is why double frees are hard to trace.
- How does free know how many bytes to release? The allocator stores the size in its own metadata, usually just before the block. You never pass a size, and you must pass exactly the pointer malloc returned.
- How do you find a memory leak? AddressSanitizer with leak detection, Valgrind on Linux, or the platform's leak tools. Then fix ownership: decide which function frees each allocation and write it down in the interface.
- What does malloc(0) return? Either NULL or a unique pointer you may pass to free but must not dereference. It is implementation-defined, so code should not rely on either.
- Stack or heap for a large buffer? The heap, or a static buffer. Stack size is limited and a big local array can overflow it, often with a crash that has no useful message.
#include <stdlib.h>
/* Doubles the capacity of *buf. Returns 0 on success, -1 on failure.
On failure *buf is unchanged and still owned by the caller. */
int grow(int **buf, size_t *cap) {
size_t new_cap = *cap ? *cap * 2 : 8;
int *tmp = realloc(*buf, new_cap * sizeof **buf);
if (tmp == NULL) {
return -1;
}
*buf = tmp;
*cap = new_cap;
return 0;
}Strings and buffer overflows
| Question | What it tests | What a strong answer shows |
|---|---|---|
strlen(s) versus sizeof s? | Terminator and decay | strlen counts characters before the NUL at run time. sizeof is a compile-time size: the whole array including the NUL, or the size of a pointer if s is a char *. |
Why is char *s = "hi"; s[0] = 'H'; a bug? | Literals | String literals may live in read-only memory and modifying one is undefined behavior. Use char s[] = "hi"; to get a writable copy. |
| What is a buffer overflow and how do you prevent one? | Bounds | Writing past the end of a buffer overwrites neighboring data or a return address. Track lengths, use snprintf, check every copy against the destination size, and test with sanitizers. |
Why was gets removed? | API safety | It cannot know the buffer size, so any long line overflows it. It was removed in C11. Use fgets and handle the trailing newline. |
| Does strncpy always terminate the string? | API traps | No. If the source is at least n characters long, no NUL is written. It also pads with zeros, which surprises people copying into large buffers. |
| Write your own strlen, strcpy or atoi. | Hand coding | Correct handling of the terminator, an empty string, a sign, leading whitespace and overflow in atoi. Say how you would report errors, since atoi itself cannot. |
#include <string.h>
void reverse(char *s) {
size_t n = strlen(s);
if (n < 2) return;
for (size_t i = 0, j = n - 1; i < j; i++, j--) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}Structs, unions and padding
- Why is this struct bigger than the sum of its fields? Alignment. The compiler inserts padding so each member starts at an address its type requires. A
char, adoubleand acharin that order took 24 bytes on a typical 64-bit build; reordering todouble, char, chartook 16. - How do you reduce padding? Order members from largest alignment to smallest. Packing pragmas exist but cost speed on some CPUs and can fault on unaligned access, so use them only for wire or file formats.
- Struct versus union? A struct holds all members at once. A union holds one at a time in shared storage, sized for its largest member. Unions appear in tagged variants and in protocol parsing.
- Can you compare two structs with memcmp? Not reliably. Padding bytes can hold garbage, so equal members can compare unequal. Compare field by field.
- Can you assign one struct to another? Yes, assignment copies every member. A pointer member is copied as a pointer, so both structs now share the pointed-to data: a shallow copy.
- What is a flexible array member? A last member declared
char data[];, used to allocate a header and a variable-length payload in one block. - Are bit-fields portable? Their layout, bit order and signedness of plain
intbit-fields are implementation-defined. Fine inside one program, risky for hardware registers or file formats shared across compilers.
#include <stdio.h>
#include <stddef.h>
struct loose { char flag; double value; char tag; };
struct tight { double value; char flag; char tag; };
int main(void) {
printf("%zu %zu %zu\n", sizeof(struct loose),
offsetof(struct loose, value), offsetof(struct loose, tag));
printf("%zu\n", sizeof(struct tight));
return 0;
}const, volatile, static and extern
| Question | What it tests | What a strong answer shows |
|---|---|---|
What does static mean on a local variable? | Storage duration | The variable keeps its value between calls and is initialized once, before the program starts. It lives with the globals, not on the stack. |
What does static mean on a function or global? | Linkage | Internal linkage: the name is visible only in that translation unit. It is the C way to keep helpers private. |
What does extern do? | Declarations | Declares a variable defined in another file without allocating it. Put the extern declaration in a header and the one definition in one .c file. |
When is volatile needed? | Optimizer assumptions | When a value can change outside the compiler's view: memory-mapped hardware registers, variables changed in an interrupt handler or a signal handler. It forces every read and write to happen. |
Does volatile make code thread-safe? | Common misconception | No. It gives no atomicity and no ordering between threads. Use C11 atomics or a mutex. |
| Can a variable be both const and volatile? | Combining qualifiers | Yes, such as a read-only status register: your code must not write it, but the hardware changes it. |
Is a const variable a compile-time constant in C? | C versus C++ | No. In C it cannot size a static array or be a case label. Use an enum constant or a macro for that. |
Undefined behavior and output prediction
Many C quizzes include lines such as i = i++ + ++i; and ask for the output. The honest answer is that the expression modifies i more than once without sequencing, so the behavior is undefined and different compilers or optimization levels can give different results. Interviewers who ask this are usually checking that you know the difference between three categories, and that you will not ship code that depends on luck.
- Undefined behavior: the standard places no requirement. Examples: signed integer overflow, reading an uninitialized local, out-of-bounds access, dereferencing NULL, shifting by the type's width or more, modifying a string literal.
- Unspecified behavior: one of several outcomes, not documented. Example: the order in which function arguments are evaluated.
- Implementation-defined behavior: the compiler must document its choice. Examples: the size of
int, whether plaincharis signed, right shift of a negative number. - Why does UB matter beyond crashes? Optimizers assume it never happens. A check written as
if (x + 1 < x)for signedxcan be removed entirely, because overflow "cannot" occur. - How do you catch it? Compile with warnings on (
-Wall -Wextra), run tests under UndefinedBehaviorSanitizer and AddressSanitizer, and use static analysis.
The preprocessor
- Why does a naive SQUARE macro give 5 for SQUARE(1 + 2)? Defined as
#define SQUARE(x) x * x, it expands to1 + 2 * 1 + 2. Parenthesize every parameter and the whole body. - Is SQUARE(i++) safe even with parentheses? No. The argument is evaluated twice. That is a reason to prefer
static inlinefunctions for anything with arguments. - Why wrap multi-statement macros in do { ... } while (0)? So the macro behaves like one statement after an
ifwithout braces and still needs its semicolon. - What are include guards? An
#ifndef NAME_H/#define NAME_H/#endifwrapper so a header included twice is processed once.#pragma onceis a widely supported but non-standard alternative. - What do the # and ## operators do in a macro?
#turns an argument into a string literal;##pastes two tokens into one. Useful for generating names and debug messages. - Macro or inline function? Functions give type checking, single evaluation and debugger visibility. Macros remain for conditional compilation, constants used in array sizes, and code generation.
Function pointers and callbacks
Expect to declare a function pointer, pass one as a callback, and explain where they are used: qsort and bsearch comparators, event handlers, plugin tables and state machines built from an array of handlers. A typedef makes the declarations readable. A common follow-up is the comparator itself: writing return x - y; looks fine and overflows for large values of opposite sign.
#include <stdlib.h>
static int cmp_int(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y); /* -1, 0 or 1; x - y can overflow */
}
typedef void (*handler_fn)(int event);
static void on_start(int event) { (void)event; }
static void on_stop(int event) { (void)event; }
static handler_fn handlers[] = { on_start, on_stop };
void sort_and_dispatch(int *v, size_t n, int which) {
qsort(v, n, sizeof v[0], cmp_int);
handlers[which](0);
}Bit manipulation
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Set, clear, toggle and test bit n. | Masks | x |= 1u << n, x &= ~(1u << n), x ^= 1u << n, (x >> n) & 1u. Use unsigned values so shifts into the top bit are defined. |
| Is a number a power of two? | Bit tricks | x != 0 && (x & (x - 1)) == 0, because a power of two has exactly one set bit and subtracting one flips everything below it. |
| Count the set bits. | Loops and tricks | Kernighan's loop: x &= x - 1 clears the lowest set bit, so it runs once per set bit. Mention compiler builtins for the fast path. |
| How do you check the machine's endianness? | Byte order | Store a known multi-byte value and read its first byte through an unsigned char *. For network data, convert with htonl and ntohl instead of hand-swapping. |
| Extract a 4-bit field at bits 8 to 11 of a register. | Masking and shifting | (reg >> 8) & 0xFu. To write it, clear the field with a mask, then OR in the new value shifted into place. |
| Swap two variables without a temporary. | Trick awareness | The XOR swap works but fails when both names refer to the same object and is rarely faster. Say you would use a temporary in real code. |
C coding problems to expect
- Reverse a singly linked list in place, then do it recursively and discuss stack depth.
- Detect a cycle in a linked list with two pointers moving at different speeds.
- Implement memmove so overlapping regions copy correctly, and explain why memcpy may not.
- Build a dynamic array that grows by doubling and frees cleanly.
- Write a fixed-size ring buffer for a producer and a consumer, and say what changes if an interrupt is the producer.
- Parse a line of comma-separated integers with strtol and report bad input.
Fictional example
- Interviewer
- When would you use memmove instead of memcpy?
- Candidate
- When the source and destination can overlap. memcpy is allowed to assume they don't, so with overlap its result is undefined. memmove behaves as if it copied through a temporary buffer. A simple way to implement it is to compare the addresses: if the destination starts before the source, copy forward; otherwise copy backward from the end, so you never overwrite bytes you still need to read. On a firmware project I hit exactly this when shifting a receive buffer left after consuming a header. It worked in debug builds and corrupted data with optimization on, and switching to memmove fixed it.
How to prepare for C interview questions
- Days 1 to 3: pointers until they are boringDraw boxes and arrows for every snippet. Write functions that take
int **, arrays of strings and pointers to arrays, and predict sizeof results before running them. - Days 4 to 6: memory with a sanitizer onBuild a dynamic array, a linked list and a string builder. Compile with
-fsanitize=address,undefinedand fix every report. Practice saying who owns each allocation. - Days 7 to 9: library functions by handWrite strlen, strcpy with a size limit, memmove, atoi with overflow checks and a tokenizer. Test empty input, one character and maximum values.
- Days 10 to 12: language cornersStorage classes, volatile, macros, struct layout, and a list of undefined behaviors you can name from memory with one example each.
- Days 13 and 14: mocks out loudDo two timed sessions where you explain each line as you write it. For embedded roles add register masks and an interrupt-safe queue.
Explaining pointer code while you type is harder than it looks, and it is what live rounds grade. Natively, an AI interview assistant for Mac and Windows, can sit in on a mock round on your computer: it transcribes what you say, so afterwards you can see where your explanation of a pointer-to-pointer drifted. During practice it can also read a C snippet or a problem statement from a screenshot and suggest an approach, which you can compare with your own prediction.
Questions people ask
What are the most common C interview questions?
Array versus pointer and sizeof, pointer arithmetic, malloc, calloc, realloc and free, returning a local's address, strlen versus sizeof, struct padding, static, const and volatile, macro pitfalls, undefined behavior, function pointers and setting or clearing bits.
How should I answer C output prediction questions?
Trace the memory step by step, and if the snippet modifies a variable twice without sequencing, overflows a signed int or reads out of bounds, say the behavior is undefined instead of guessing an output.
What C questions are asked for embedded roles?
volatile and why it is not a lock, bit masks on registers, endianness, struct packing for hardware layouts, interrupt-safe ring buffers, fixed-width integer types and avoiding dynamic allocation.
Which C programs should freshers practice for interviews?
String reversal, your own strlen and strcpy, atoi with error checks, linked list reversal and cycle detection, a dynamic array, memmove, and bit counting.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
