C interview questions
C questions that often come up in fresher and systems interviews, with answers that show real understanding.
An array is a fixed block of elements, and its name usually converts to a pointer to the first element when used in an expression. A pointer is a separate variable that holds an address and can be reassigned. sizeof shows the difference clearly: on an array it gives the size of the whole array, on a pointer only the size of the pointer itself.
A dangling pointer still holds the address of memory that has been freed, or of a local variable whose function has already returned. Using it is undefined behaviour and can silently corrupt data. I avoid it by setting pointers to NULL after free and never returning the address of a local variable.
Inside a function, static makes a local variable keep its value between calls, because it lives for the whole program run instead of on the stack. At file level, static limits a global variable or function to that source file, which avoids name clashes between files. A typical use is a function that counts how many times it has been called.
malloc takes a total number of bytes and leaves the memory uninitialised. calloc takes an element count and an element size, and sets every byte to zero. Both return NULL on failure, and memory from either is released with free.
C always passes arguments by value, so a function receives copies and cannot change the caller's variables directly. To get the effect of call by reference, you pass a pointer and the function changes the value through it. A swap function shows this: swap(int *a, int *b) works, while swap(int a, int b) changes nothing for the caller.
A memory leak happens when allocated memory is never freed and the program loses every pointer to it, so memory use grows over time. I prevent leaks by giving each allocation a clear owner responsible for freeing it, paying special attention to early returns and error paths. To find them, tools such as Valgrind or AddressSanitizer report allocations that were never released.
Practise out loud. Say each answer once as written, then again in your own words with your own number or story.
Have a number ready. "My C score is at benchmark on a timed test" is a stronger answer than "I am good at it". Take the test and quote the result.
More in Programming