You're on a screening call, and the interviewer asks what happens when a pointer outlives the memory it references. You give the definition of a dangling pointer. Then they ask which function owns the allocation, whether another pointer still references it, and how you'd verify the fix.
That's where a memorised answer stops helping.
Interviewers are listening for a working model of C: what exists in memory, how long it remains valid, and which operations the language permits. A strong candidate explains the code, names the risk, and proposes a test without pretending that a successful compilation proves correctness.
For recruitment teams, the distinction matters. A candidate who confidently predicts an output for undefined behaviour may sound more convincing than someone who correctly refuses to invent one. Score the reasoning, not just the speed of the response.
These C questions with answers connect short spoken explanations to practical code and probing follow-ups. They're useful for candidates preparing for screening rounds and hiring managers who want technical interviewers to distinguish familiarity from competence.
A useful screening answer explains what the code does, when it stops being valid, and how the candidate would check it.
1. What is the difference between malloc() and calloc()?
What the interviewer is probing: Allocation size, initialisation, and failure handling. Knowing the function signatures isn't enough if the candidate immediately reads uninitialised memory.
Say it aloud: malloc() allocates the requested number of bytes without initialising them. calloc() allocates space for a count of elements and sets every byte to zero. Both return a null pointer on allocation failure, and successful allocations must eventually be released with free().
#include
#include
int *make_counts(size_t n)
{
int *counts;
if (n == 0 || n > SIZE_MAX / sizeof *counts)
return NULL;
counts = calloc(n, sizeof *counts);
if (counts == NULL)
return NULL;
return counts; /* Caller owns this allocation. */
}
This is appropriate for a frequency-counting buffer whose elements must initially represent zero. If every element will immediately be overwritten, malloc() avoids requesting initialisation you don't need, although actual performance depends on the allocator and workload.
The follow-up that separates strong candidates
Ask whether zeroed bytes guarantee a null pointer or floating-point zero for every possible type. They don't: calloc() promises an all-bits-zero representation, not every type's semantic zero value.
Listen for explicit size-overflow checks and sizeof *counts, which stays aligned with the pointed-to type. Don't reward a blanket claim that one allocator is always faster.
2. What is a pointer, and how does pointer arithmetic work?
Start with an array traversal rather than an abstract definition. Ask the candidate to identify the object, the pointer, and the value obtained by dereferencing it.
int readings[] = {12, 18, 24};
int *p = readings;
int *end = readings + sizeof readings / sizeof readings[0];
for (; p != end; ++p) {
*p += 1;
}
Say it aloud: A pointer holds an address identifying an object or function, or a null pointer value. Arithmetic on an object pointer advances in units of its pointed-to type, so incrementing an int * advances to the next integer element.
What the interviewer is probing: Whether the candidate understands array boundaries, not merely address notation. readings[i] and *(readings + i) designate the same element when the index is valid.
The pointer end may be formed and compared, but it mustn't be dereferenced. Arithmetic must remain within the same array object or reach its one-past position; an accessible-looking neighbouring address doesn't make an operation valid.
Ask about boundaries, not guessed addresses
A strong follow-up is whether subtracting pointers from unrelated allocations is valid. It isn't defined pointer subtraction, even if both allocations happen to sit close together.
Initialising an otherwise uninitialised pointer to NULL makes its state explicit. It doesn't make dereferencing that pointer safe.
3. What is the difference between const char *p, char *const p, and const char *const p?
Say it aloud: const char *p allows reassignment of the pointer but prevents modifying characters through it. char *const p fixes the pointer but allows modification of the characters. const char *const p prevents both operations through that declaration.
What the interviewer is probing: Whether the candidate can read an interface and understand which operations it permits. Read outward from the identifier, distinguishing the pointer from the pointed-to type.
char text[] = "cat";
const char *view = text;
char *const fixed = text;
const char *const fixed_view = text;
view = "dog"; /* Allowed: view can point elsewhere. */
fixed[0] = 'b'; /* Allowed: text is writable. */
/* fixed = text + 1; */ /* Not allowed. */
/* fixed_view[0] = 'r'; */ /* Not allowed. */
For a read-only string-processing function, a const char * parameter communicates that the function won't modify characters through that parameter. It doesn't promise that nobody else can change the underlying object.
Test the underlying object's mutability
Ask whether casting away const always causes undefined behaviour. The cast itself isn't the decisive issue; modifying an object originally defined as const is.
A writable array accessed through a const-qualified view remains a writable underlying object. A string literal, however, mustn't be modified, even if a permissive declaration lets someone assign its address to char *.
4. What is the difference between ++i and i++, and why is i = i++ + ++i undefined behavior?
What the interviewer is probing: Whether a candidate distinguishes defined language semantics from whatever a particular executable happens to print.
Say it aloud: Prefix increment produces the incremented value; postfix increment produces the previous value while also incrementing the object. In i = i++ + ++i, modifications of i are unsequenced relative to each other, so the expression has undefined behaviour.
int i = 0;
int previous = i++; /* previous receives the old value. */
int current = ++i; /* current receives the new value. */
/* Don't execute this:
i = i++ + ++i;
*/
For an ordinary loop where the increment expression's value is discarded, either increment form works. In C, claiming that prefix increment is faster for a scalar integer is a poor substitute for examining generated code.
Don't ask candidates to predict a portable output for undefined behaviour. Ask them to identify the violated rule and replace the expression with explicit steps.
A better follow-up
Ask whether parentheses fix the original expression. They don't: grouping operands doesn't establish the sequencing needed here.
Enable compiler diagnostics such as -Wall and -Wextra, and use UndefinedBehaviorSanitizer where appropriate. These tools help detect mistakes, but neither warnings nor runtime instrumentation can prove that every undefined operation has been eliminated.
A strong candidate also notes that signed increment can overflow at the type's limit.
5. What is the difference between stack and heap memory, and what do static, auto, and register storage classes mean?
Say it aloud: Ordinary local variables generally have automatic storage duration, while dynamically allocated objects last until they're released. Static objects last for the program's execution. Stack and heap describe common implementation arrangements, not memory regions that the C language requires.
#include
int next_ticket(void)
{
static int ticket; /* Initially zero; persists across calls. */
return ++ticket; /* Simplified: assumes no overflow. */
}
int *make_value(void)
{
int *p = malloc(sizeof *p);
if (p != NULL)
*p = 42;
return p; /* Caller must free it. */
}
What the interviewer is probing: Whether the candidate connects lifetime to API design. Returning a pointer to an ordinary local variable is invalid once that object's lifetime ends, regardless of whether its old bytes appear unchanged.
Look beyond the memory diagram
In traditional C declarations, auto explicitly specifies the usual automatic storage class for a local variable. register is an optimisation hint, not a guarantee of CPU-register placement; under traditional rules, it also prevents taking the object's address.
Use a declared language standard when testing these keywords because newer C revisions change some declaration rules.
For a practical extension, use an expression parser from these infix-to-postfix questions and ask who owns its stack buffer. Then ask why the static ticket counter would need redesign for concurrent calls.
6. What is the difference between a structure and a union?
A structure stores all its members as distinct subobjects. A union provides overlapping storage for its members, which makes it useful when a value has alternative representations.
Say it aloud: A struct can hold all its member values simultaneously. A union shares storage among its members, so I track which member currently represents the value, usually with a separate tag.
enum value_kind { VALUE_INT, VALUE_DOUBLE };
struct value {
enum value_kind kind;
union {
int integer;
double real;
} data;
};
struct value sample = {
.kind = VALUE_DOUBLE,
.data = { .real = 3.5 }
};
What the interviewer is probing: Representation, alignment, and whether memory savings justify additional state management. The tagged union above suits a parser that accepts either integer or floating-point values.
Ask what sizeof actually guarantees
A structure may include padding between members and at its end. A union must accommodate its largest member and satisfy alignment requirements, so neither layout should be guessed from member names.
- Inspect layout: Use
sizeof,_Alignof, andoffsetofwhere applicable on the target platform. - Maintain the tag: Update the discriminator whenever the stored variant changes.
- Avoid raw serialisation: Writing a struct's bytes directly to a file exposes padding, byte-order, and representation differences.
A useful follow-up asks whether reading another union member is a portable conversion. It isn't a general-purpose substitute for an explicit numeric conversion.
7. How do you reverse a string in C, and how do you swap two variables without a temporary variable?
What the interviewer is probing: Boundary handling and engineering judgement. These exercises become useful only when candidates explain their input assumptions and reject unsafe shortcuts.
Say it aloud: I reverse a writable, null-terminated byte string by swapping characters from its ends towards the centre. For ordinary variable swapping, I prefer a temporary because arithmetic and XOR tricks introduce unnecessary risks.
#include
void reverse(char *s)
{
if (s == NULL)
return;
size_t right = strlen(s);
for (size_t left = 0; left < right; ++left) {
--right;
if (left >= right)
break;
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
}
}
The terminator stays in place, and empty strings don't cause an unsigned-index underflow. Runtime grows linearly with string length, while auxiliary storage stays constant.
Challenge the shortcut
Arithmetic swapping can overflow signed integers. XOR swapping works for suitable integer objects but fails if both operands refer to the same object unless explicitly guarded.
Ask whether the function reverses user-visible Unicode characters correctly. It reverses bytes, so it can corrupt a multibyte encoding such as UTF-8.
Use a coding test in C to evaluate the implementation against empty, single-character, and odd-length inputs rather than rewarding an elaborate swap trick.
8. What are dangling pointers, memory leaks, and double free errors?
Say it aloud: A dangling pointer refers to an object whose lifetime has ended. A memory leak occurs when allocated storage isn't released as required, often because its owning reference is lost. Double free means attempting to release the same allocation again, which causes undefined behaviour.
#include
void example(void)
{
int *owner = malloc(sizeof *owner);
if (owner == NULL)
return;
int *alias = owner;
*owner = 7;
free(owner);
owner = NULL;
/* alias is dangling. Don't dereference or free it. */
}
What the interviewer is probing: Ownership across aliases and error paths. Setting owner to NULL prevents accidental reuse through that variable, but it doesn't update alias or any other stored reference.
Follow the allocation through failure
Ask how cleanup works when a function allocates a buffer and then fails to open a file. A single cleanup label can keep resource release readable without duplicating it across branches.
Ownership rule: Every allocated object needs a clear owner, a documented transfer policy, and an eventual release path.
Run relevant tests with AddressSanitizer or Valgrind. A clean test run isn't proof of safety, but a candidate should know how to investigate use-after-free and leak reports.
For broader technical-round interview questions, extend this example across function boundaries and ask whether returned pointers are borrowed or owned.
9. What is the difference between sizeof on an array and sizeof on a pointer, and what is array decay?
Give the candidate an array parameter declaration and ask what information the function receives. This exposes misunderstandings that a definition-only question misses.
#include
int sum(const int values[], size_t length)
{
int total = 0;
for (size_t i = 0; i < length; ++i)
total += values[i];
return total; /* Assumes the sum fits in int. */
}
int example(void)
{
int values[] = {4, 8, 12};
size_t length = sizeof values / sizeof values[0];
return sum(values, length);
}
Say it aloud: sizeof applied to an actual array gives its total byte size. In most expressions, an array converts to a pointer to its first element. An array parameter declaration is adjusted to a pointer parameter, so sizeof that parameter gives the pointer's size.
What the interviewer is probing: Whether the candidate preserves length information when designing interfaces. An array parameter doesn't carry its element count into the function.
Change the example
Ask what happens if values in the caller becomes a dynamically allocated pointer. The length expression no longer counts array elements; it divides a pointer size by an element size.
Strong candidates also recognise that sizeof and unary address-of are important exceptions to ordinary array conversion. They don't assume pointer size or integer size from the machine's marketing description.
10. What is the difference between a macro and a function, and what are common macro pitfalls?
Say it aloud: A function-like macro substitutes preprocessing tokens, while a function has typed parameters and each argument expression is evaluated once per call. Parentheses prevent many precedence errors in macros, but they don't prevent repeated evaluation.
#define BAD_SQUARE(x) x * x
#define SQUARE(x) ((x) * (x))
static inline int square_int(int x)
{
return x * x;
}
int example(void)
{
int value = 3;
int result = square_int(value++);
return result;
}
What the interviewer is probing: Whether candidates inspect expanded code instead of treating macros like ordinary calls. BAD_SQUARE(a + 1) groups incorrectly; SQUARE(value++) introduces unsequenced modifications despite the improved parentheses.
Test judgement, not a blanket ban
The inline function avoids repeated argument evaluation and provides a typed interface. Its multiplication can still overflow for signed inputs, so replacing a macro doesn't automatically make the arithmetic safe.
- Prefer typed operations: Use
static inlinefunctions for ordinary calculations. - Keep legitimate macros: Conditional compilation and token manipulation still need preprocessing facilities.
- Inspect expansions: Use
gcc -Ewhen a macro's behaviour isn't obvious.
A useful follow-up asks whether function arguments are evaluated left to right. They aren't guaranteed to be in C; evaluating each argument once doesn't establish their relative order.
Also distinguish a const-qualified object from an integer constant expression. A const int isn't interchangeable with a macro constant in every C context.
How the 10 C Interview Questions Compare at a Glance
| Item | Core Topic | Skill Tested | Best For |
|---|---|---|---|
| Difference between malloc() and calloc() | Dynamic memory allocation and initialization | Heap allocation, zero-initialization, and error checking | Screening memory management skills |
| Pointer and pointer arithmetic | Memory addresses and type-scaled arithmetic | Dereferencing, address operations, and array relationships | Assessing core C knowledge |
| Difference between const pointer declarations | const qualifiers on pointers and data | Reading and reasoning about C declarations | Distinguishing mid-level and senior candidates |
| Difference between ++i and i++; undefined behavior in expressions | Increment operators and sequencing | Understanding side effects and undefined behavior | Evaluating reliable C coding practices |
| Stack, heap, and storage classes | Memory regions, storage duration, and scope | Understanding variable lifetime and memory management | Systems and embedded roles |
| Difference between a structure and a union | Composite types and shared memory | Understanding layout, alignment, and member storage | Systems and performance-sensitive work |
| Reversing a string and swapping variables | In-place string manipulation and swapping | Algorithm implementation, complexity, and edge cases | Coding assessments |
| Dangling pointers, memory leaks, and double free errors | Heap memory safety | Recognizing and preventing memory management errors | Systems, embedded, and security roles |
| sizeof on arrays and pointers; array decay | Array and pointer behavior | Understanding sizeof, function parameters, and array decay | Checking practical C experience |
| Difference between a macro and a function | Preprocessor substitution and function behavior | Identifying macro pitfalls and safer alternatives | Embedded and large codebase roles |
Turn These Answers into Practice Rounds
Knowing the answers is only half the preparation. Practise explaining each answer aloud in under two minutes, then write the code by hand and trace the memory layout. Start with allocation, pointer boundaries, and memory ownership because mistakes there affect the correctness of otherwise straightforward programs.
For candidates, rehearsal should include interruption. Have a partner change an assumption: the input is empty, allocation fails, another pointer aliases the buffer, or the function now runs concurrently. Your explanation should adapt without collapsing into a different memorised answer.
Practise reasoning under changed assumptions
Pick three questions today: allocation, string reversal, and array decay make a useful combination. Explain the contract before coding, identify invalid inputs, and describe how the caller learns about failure. Then compile the implementation with warnings enabled and test the edge cases you named.
C remains part of formal academic preparation in India: Bharathiar University's Statistics syllabus includes pointers, structures, file handling, and statistical applications. Hiring teams can build on that foundation by asking candidates to process a small dataset while explaining buffer ownership and numerical assumptions.
For recruitment leaders, distinguish a preparation exercise from evidence of job readiness. A familiar reversal exercise can establish basic control-flow competence, but it doesn't establish readiness to maintain an embedded driver or concurrent service. Match the follow-up to the work the successful candidate will perform.
Score the explanation alongside the code
Use separate evaluation criteria rather than a single impression of technical confidence:
- Correctness: Does the implementation satisfy its stated contract?
- Memory safety: Does the candidate respect bounds, lifetime, and ownership?
- Testing: Do they propose cases that could expose their own mistakes?
- Communication: Can they explain assumptions and revise an answer when challenged?
Publish the compiler standard, permitted libraries, input constraints, and assessment format before the interview. Allow candidates to ask clarifying questions, and distinguish concise technical reasoning from polished spoken English.
Organisations using Career Central can combine AI phone screening with coding assessments to examine explanations alongside technical tasks. Our team-review process keeps candidate responses and structured insights available to hiring teams, who make the final decision.
Choose the questions that expose decisions your engineers face at work. A candidate who explains why a tempting solution is unsafe often provides more useful hiring evidence than one who reproduces a familiar answer without understanding its limits.
Career Central offers AI-driven phone screening, first-round interviews, and coding assessments for organisations. Visit Career Central to connect C screening questions with practical coding tasks and structured evaluation centred on your role requirements.