Programming using C
Interview Questions with Answers

1. Explain the structure of a C program.

Answer:
A typical C program is composed of the following parts:

#include <stdio.h>      // Preprocessor directive
// Global variable declarations (if any)

int main()              // Main function - entry point
{
   // Variable declarations
   // Executable statements
   return 0;
}

// User-defined functions (if any)

Key components:

  • Preprocessor Directives: Start with # (e.g., #include <stdio.h>) to include files or define macros.
  • main() Function: Mandatory function where program execution begins.
  • Declarations: Variable and function declarations.
  • Statements: Executable code within {}.
  • Functions: Reusable blocks of code defined by the user or standard libraries.

Every expert was once a beginner. Start your journey in C today!

2. What are the key features of the C programming language?

Answer:
C is a procedural, general-purpose programming language developed by Dennis Ritchie. Its key features include:

  • Simplicity: Small set of keywords, easy syntax.
  • Portability: Programs written in C can run on different systems with minimal or no modification.
  • Modularity: Code can be split into reusable functions.
  • Efficiency and Speed: Low-level memory access through pointers; compiled directly to machine code.
  • Structured Programming: Encourages use of functions and control structures like loops and conditionals.
  • Rich Library Support: Provides a variety of built-in functions.
  • Low-level Manipulation: Ability to interact directly with hardware or memory (like an assembly language).

3. What is the role of main() function in C?

Answer:
The main() function is the entry point of any C program. The execution of the program begins from this function.

int main() {
    // Code to execute
    return 0;
}

Roles of main():

  • Initializes program execution.
  • Returns an integer value to the operating system (0 typically denotes successful execution).
  • Can take arguments: int main(int argc, char *argv[]).

4. How is C different from C++?

Answer:

FeatureCC++
ParadigmProceduralMulti-paradigm (Procedural + OOP)
EncapsulationNot supportedSupported via classes
InheritanceNot supportedSupported
Function OverloadingNot supportedSupported
Data hidingLimited (via static)Fully supported using private/protected access
TemplatesNot availableSupported
NamespaceNot availableSupported
Exception HandlingNot supportedSupported

In summary, C++ is an extension of C with Object-Oriented features.

5. What are keywords and identifiers in C?

Answer:

  • Keywords: Reserved words with special meaning in C.
    • Cannot be used as variable names. Example: int, return, if, while, etc.
    • C has 32 keywords (in C89), e.g., auto, break, const, continue, etc.
  • Identifiers: Names used by the programmer to identify variables, functions, arrays, etc.
    • Must begin with a letter or underscore, followed by letters, digits, or underscores.
    • Cannot use keywords as identifiers.

 Example

int marks;       // 'int' is keyword, 'marks' is identifier

6. What is the difference between const, volatile, and static keywords?

Answer:

  • const: Declares a variable as constant. Its value cannot be changed after initialization.

const int a = 10;

  • volatile: Tells the compiler not to optimize the variable because its value may change unexpectedly (e.g., hardware registers, multi-threading).

volatile int sensorValue;

  • static:
    • Inside a function: retains its value across function calls (local persistence).
    • Outside a function: limits the visibility of the function/variable to the current file (internal linkage).
static int count = 0; // Retains value between calls

7. What is a header file and why is it used?

Answer:
A header file in C contains declarations of functions, macros, constants, and types to be shared across multiple files.

  • Uses the .h extension (e.g., stdio.h, stdlib.h).
  • Prevents code repetition and helps in modular programming.
  • Included at the top using #include directive. 

Example

#include <stdio.h>  // Contains declaration of printf(), scanf(), etc. 

Custom header file

// mathutils.h
int add(int a, int b);
#include "mathutils.h"

8. What are the different data types supported by C?

Answer:
C supports several basic and derived data types.

  1. Basic Data Types:
    • int – Integer values
    • float – Floating-point values
    • double – Double-precision floating-point
    • char – Single character
    • void – Represents absence of value (used in functions)
  2. Derived Data Types:
    • Arrays
    • Pointers
    • Structures
    • Unions
    • Functions
  3. Enumeration Types:
    • enum for defining named constants
  4. Modifiers:
    • short, long, signed, unsigned can be used with int, char, etc.

9. What is the difference between int, long, and short?

Answer:

TypeDescriptionTypical Size (32-bit systems)
shortSmaller range of integers2 bytes (-32,768 to 32,767)
intStandard integer4 bytes (-2,147,483,648 to 2,147,483,647)
longLarger range of integers4        or 8 bytes depending on system

All types can be signed or unsigned.

short int x;        // or short x;

long int y;          // or long y;

10. What is the use of typedef in C?

Answer:
typedef is used to create an alias (new name) for existing data types. It improves code readability and manageability, especially for complex types like structures or pointers. 

Syntax

typedef existing_type new_name; 

Example 1 – Simple Type

typedef unsigned int uint;
uint x = 10;

Example 2 – Structure

typedef struct {
    int id;
    char name[50];
} Student;
Student s1;

11. Explain the scope and lifetime of variables in C.

Answer:

  • Scope refers to the region of the program where a variable can be accessed or referenced.
  • Lifetime refers to the duration of time during program execution for which the variable exists in memory.
TypeScopeLifetime
LocalInside a block or functionCreated when function is called, destroyed on return
GlobalEntire programExists for entire program execution
StaticScope depends on declaration locationRetains value across function calls, exists until program ends
Function ParameterLocal to functionLifetime ends when function returns

 Example

int globalVar = 5;           // Global scope and lifetime
void func() {
    static int x = 0;            // Local scope, static lifetime
    int y = 10;                     // Local scope and lifetime
}

12. What is the difference between global and static variables?

Answer:

FeatureGlobal VariableStatic Variable
ScopeAvailable throughout the entire programLimited to the block or file where it is declared
LifetimeEntire duration of program executionEntire duration of program execution
VisibilityExternally visible across files (unless restricted with static)Not visible outside the block/file
DeclarationOutside all functionsCan be inside or outside functions

 Example

int g = 10;                          // Global variable
void demo() {
    static int s = 0;           // Static local variable
    s++;
    printf("%d\n", s);
}

13. What are lvalue and rvalue in C?

Answer:

  • lvalue (Left value): Refers to an object that has an identifiable location in memory (i.e., a variable).
  • rvalue (Right value): Refers to a temporary value or constant that does not have a memory address.

Rules:

  • lvalue can appear on both the left and right side of an assignment.
  • rvalue can only appear on the right side.

 Examples

int x = 10;          // ‘x’ is lvalue, ’10’ is rvalue

x = x + 5;             // both sides use lvalue ‘x’, rvalue ‘5’ and ‘x + 5’

5 = x;                    // Invalid: rvalue cannot be on the left

14. What is the difference between ++i and i++?

Answer:

ExpressionNameAction
++iPre-incrementIncrements the value of i before using it in the expression
i++Post-incrementUses the current value of i in the expression, then increments it

Example

int i = 5;
printf("%d\n", ++i);      // Output: 6 (i becomes 6, then printed)
printf("%d\n", i++);      // Output: 6 (printed first, then becomes 7)

Both ultimately increment i, but the timing of the increment differs.

15. What is typecasting in C?

Answer:
Typecasting is the explicit conversion of a variable from one data type to another. It helps in performing operations involving mixed data types.

 Syntax

(new_type) expression;

 Example

int a = 5, b = 2;
float result;
result = (float)a / b;     // Output: 2.5

Without casting, a / b would result in integer division (2).

16. What is the difference between structure and union in C?

Answer:

Both structures and unions are used to group different types of variables under one name. However, they differ in how memory is allocated and used.

FeatureStructure (struct)Union (union)
Memory AllocationEach member has its own memory spaceAll members share the same memory space
SizeSum of all members’ sizesSize of the largest member
AccessAll members can be accessed at the same timeOnly one member is valid at any given time
Use CaseWhen storing multiple values simultaneouslyWhen storing one value at a time

Structure Example

#include <stdio.h>
struct Student {
    int id;
    float marks;
};
int main() {
struct Student s = {101, 92.5};
printf("ID: %d, Marks: %.2f\n", s.id, s.marks);
return 0;
}

Union Example

#include <stdio.h>
union Data {
    int i;
    float f;
};
int main() {
    union Data d;
    d.i = 10;
    printf("Integer: %d\n", d.i);
    d.f = 5.5;
    printf("Float: %.2f\n", d.f);  // Overwrites previous data
    return 0;
}

Use struct when you want to store multiple independent values.

Use union when you want to save memory and only need one value at a time.

17. How does short-circuit evaluation work in C?

Answer:

Short-circuit evaluation means that in logical expressions using && (AND) or || (OR), C does not evaluate the second operand if the result is already determined by the first.

OperatorBehavior
&&If first operand is false, second is not evaluated
||Evaluate each operand, until get false

 Example

int x = 0;
if (x != 0 && 10/x > 1) {  // 10/x not evaluated; prevents divide-by-zero
    printf("Valid");
}

This improves performance and prevents runtime errors.

18. What is the sizeof() operator and how is it used?

Answer:

sizeof() is a compile-time operator used to determine the memory (in bytes) occupied by a variable or data type.

 Syntax

sizeof(variable) or sizeof(type)

 Examples

int x;
printf("%lu", sizeof(x));       // Output: 4 (on 32-bit/64-bit systems)
printf("%lu", sizeof(double));  // Output: 8

Useful in:

  • Memory allocation
  • Writing portable code
  • Determining array size:
int arr[10];
int size = sizeof(arr) / sizeof(arr[0]);  // size = 10

19. What are the different storage classes in C?

Answer:

Storage classes define the scope, lifetime, default value, and linkage of variables.

Storage ClassScopeLifetimeDefault ValueUsage
autoLocalFunction callGarbageDefault for local variables
registerLocalFunction callGarbageSuggests storing in CPU register
staticLocal/GlobalEntire program0 (if uninit.)Preserves value across function calls
externGlobal (external)Entire programValue from other fileAccess global variable from another file

 Example

static int count = 0;    // Static storage
extern int totalMarks;   // External variable from another file

20. What is the precedence and associativity of operators?

Answer:

  • Precedence: Determines which operator is evaluated first in an expression with multiple operators.
  • Associativity: Determines the order of evaluation when two operators have the same precedence.

 Example

int x = 10 + 2 * 3;  // Multiplication (*) has higher precedence than addition (+)

 Associativity Table (Simplified)

Operator GroupAssociativity
() [] -> .Left to Right
++ — (postfix)Left to Right
+ – * / %Left to Right
= += -= etc.Right to Left
&& ` 

Use parentheses () to override default precedence for clarity:

int x = (10 + 2) * 3;  // Now addition happens first

Success in interviews begins with smart preparation. This is your first step!

21. What is the difference between while and do-while loop?

Answer:

Featurewhile Loopdo-while Loop
Condition CheckAt the beginningAt the end
ExecutionLoop body may never execute if condition is false initiallyLoop body executes at least once
Syntaxwhile(condition) { … }do { … } while(condition);

 Example

int i = 0;
// while loop
while (i < 5) {
    printf("%d ", i);
    i++;
}
// do-while loop
do {
    printf("%d ", i);
    i++;
} while (i < 5);

22. How does the for loop work internally?

Answer:

A for loop has the structure:

for (initialization; condition; increment) {

// loop body

}

 Execution steps:

  1. Initialization (runs once at the start)
  2. Condition check
    • If true, execute loop body.
    • If false, exit the loop.
  3. Increment or Update
  4. Go back to step 2.

 Example

for (int i = 0; i < 3; i++) {
    printf("%d ", i);
}

Internally, it works like:

int i = 0;
while (i < 3) {
    printf("%d ", i);
    i++;
}

23. What is the use of break and continue statements?

Answer:

  • break:
    • Immediately terminates the loop or switch.
    • Control moves to the statement after the loop or switch.
  • continue:
    • Skips the current iteration and jumps to the next loop cycle.

 Example – break

for (int i = 1; i <= 5; i++) {
    if (i == 3)
        break;
    printf("%d ", i);           // Output: 1 2
}

Example – continue

for (int i = 1; i <= 5; i++) {
    if (i == 3)
        continue;
    printf("%d ", i);           // Output: 1 2 4 5
}

24. How does switch-case work and what is its fall-through behavior?

Answer:

A switch statement executes code based on matching a case label with the provided expression.

 Syntax

switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // default code
} 

Fall-through behavior:

  • If break is not used, execution continues to the next case, even if it does not match.
  • This is known as fall-through.

 Example

int grade = 2;
switch (grade) {
    case 1:
    case 2:
        printf("Good\n");  // Fall-through: case 1 and 2 share output
        break;
    case 3:
        printf("Average\n");
        break;
    default:
        printf("Invalid\n");
}

25. What is a nested loop? Give an example.

Answer:

A nested loop is a loop inside another loop. It is used when we need to perform repetitive operations within another repetitive operation, such as matrix traversal or pattern printing.

 Example

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        printf("i=%d, j=%d\n", i, j);
    }
}

26. How is goto used and why is it discouraged?

Answer:

  • goto is a control transfer statement that jumps to a labeled part of code.

Syntax

goto label;
...
label:
// code to execute

 Example

int x = 1;
if (x == 1)
    goto skip;
printf("This will not print\n");
skip:
printf("Goto executed\n");

 Why it’s discouraged:

  • Makes code hard to read, debug, and maintain.
  • Violates structured programming principles.
  • Can lead to spaghetti code if misused.

Use loops and functions instead of goto whenever possible.

27. Can return be used to exit a loop?

Answer:

Yes. The return statement can exit not only the loop but also the entire function.

Example

void findNumber(int arr[], int size, int target) {

    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            printf("Found\n");
            return;  // Exits loop and function
        }
    }
    printf("Not Found\n");
}

 Note: Use break if you only want to exit the loop without terminating the function.

28. What is the difference between if-else and switch?

Answer:

Featureif-elseswitch
Data TypesWorks with any condition (int, char, float, string)Works with discrete values only (int, char)
ExpressionsAllows relational and logical expressionsAllows exact match only
FlexibilityMore flexible and powerfulLess flexible, but faster for multiple cases
Use CaseComplex conditions, rangesMenu selections, value-based branching

 Example using switch

switch (choice) {
    case 1: // do task A
    case 2: // do task B
}

 Example using if-else

if (score >= 90) { ... }
else if (score >= 80) { ... }

29. What are infinite loops? Give an example.

Answer:

An infinite loop is a loop that never terminates, either due to a condition that is always true or a missing termination condition.

Use Cases: Game engines, OS kernels, server processes.

 Example using while

while (1) {
// infinite loop
}

 Example using for

for (;;) {
// infinite loop
}

 Example using do-while

do {
// infinite loop
} while (1);

30. How do you prevent logical errors in control structures?

Answer:

To prevent logical errors (which compile but produce wrong results), follow these best practices:

  • Clearly define logic and flow before coding (e.g., use flowcharts or pseudocode).
  • Use meaningful variable and function names to avoid confusion.
  • Test with different input cases – normal, boundary, and edge cases.
  • Use debugging tools and printf() for tracing flow.
  • Avoid deeply nested loops or conditions – refactor into functions.
  • Comment your code and follow consistent indentation.
  • Use break, continue, return judiciously – avoid excessive jumping.
  • Write unit tests for each block of logic.

31. What is a function pointer? Give an example.

Answer:

A function pointer is a pointer that stores the address of a function and can be used to call the function indirectly.

Syntax

return_type (*pointer_name)(parameter_list);

Example

#include <stdio.h>
void greet() {
    printf("Hello from function pointer!\n");
}
int main() {
    void (*fp)();                  // Declare function pointer
    fp = greet;                    // Assign address of greet
    fp();                          // Call function using pointer
    return 0;
}

Function pointers are useful for callbacks, dynamic function selection, and implementing polymorphism in C.

32. What is the difference between call by value and call by reference in C?

Answer:

FeatureCall by ValueCall by Reference (via Pointers)
Passing MechanismCopies the value into the functionPasses the address of the variable
Effect on Original VariableNo changeChanges affect the original variable
Default in CYesNo (must use pointers manually)

 Example

void modifyValue(int x) {
    x = 100;
}
void modifyReference(int *x) {
    *x = 100;
}
int main() {
    int a = 10;
    modifyValue(a);              // a remains 10
    modifyReference(&a);         // a becomes 100
}

33. What are inline functions? Are they available in C?

Answer:

An inline function is a function where the compiler replaces the function call with the actual function code to eliminate overhead.

  • Introduced in C99 standard using the inline keyword.
  • It’s only a request to the compiler; not mandatory.
  • Mostly used for small, frequently called functions.

 Syntax (C99)

inline int square(int x) {
    return x * x;
}

Note: Inline functions in C are less powerful than in C++ (C does not support default arguments, function overloading, etc.).

34. What is recursion? Give an example.

Answer:

Recursion is a process in which a function calls itself directly or indirectly to solve a problem by breaking it into smaller sub-problems.

 Example – Factorial

int factorial(int n) {
    if (n == 0) return 1;
    return n * factorial(n - 1);
}

Usage: Problems like factorial, Fibonacci, Tower of Hanoi, tree traversals, etc.

35. What are the advantages and disadvantages of recursion?

Answer:

Advantages:

  • Simplifies complex problems.
  • Cleaner code for tree and graph algorithms, backtracking, etc.
  • Natural fit for problems with recursive structure.

Disadvantages:

  • High memory usage (stack frames).
  • Risk of stack overflow if not written properly.
  • Usually slower than iteration due to overhead of function calls.

36. What are storage classes and their impact on functions?

Answer:

Storage classes in C determine scope, visibility, lifetime, and linkage of variables and functions.

Storage ClassFor FunctionsImpact
externDeclares external functionAccessible across multiple files
staticStatic functionRestricted to current file only
autoNot used with functionsApplies only to local variables
registerNot applicable to functionsUsed for fast access variables

 Example of static function

static void helper() {
// This function is accessible only in this file
}

37. Can you return multiple values from a function in C?

Answer:

C functions cannot return multiple values directly, but you can achieve this by:

  1. Using pointers as arguments:
void calc(int a, int b, int *sum, int *prod) {
    *sum = a + b;
    *prod = a * b;
}
  1. Using a structure:
struct Result {
    int sum;
    int prod;
};
struct Result calc(int a, int b) {
    struct Result r = {a + b, a * b};
    return r;
}

38. What is a static function?

Answer:

A static function in C is a function declared with the static keyword, which restricts its visibility to the current source file.

  • Cannot be accessed from other files (no external linkage).
  • Helps in encapsulation and modular design.

 Example

static void logError() {
    printf("Error occurred\n");
}

Useful in library or utility files where helper functions should not be exposed externally.

39. What is the default return type of functions in C?

Answer:

Before C99, if no return type is specified, C defaults the return type to int.

Example (Old Style)

func() {  // Treated as int func()
    return 5;
}

However, in modern C standards (C99 and later), explicit declaration is mandatory. Implicit int is considered deprecated or invalid.

Best Practice: Always declare the return type explicitly.

40. What is the purpose of void in function declaration?

Answer:

void has two main purposes in function declarations:

  1. As return type – Indicates the function does not return any value.
void greet() {
printf("Hello!\n");
}
  1. As parameter list – Indicates the function does not accept any parameters.
void show(void) {
printf("Nothing to input\n");
}

Using void improves code readability and helps the compiler catch errors.

The more you practice, the closer you get to your dream job. Begin now!

41. What is the difference between an array and a pointer?

Answer:

FeatureArrayPointer
Memory AllocationAllocated at compile timeCan point to dynamically allocated memory
Name BehaviorFixed address (non-modifiable)Can be reassigned to another location
Size InformationSize is known at compile timePointer has no size information
Declarationint arr[5];int *ptr;

 Example

int arr[3] = {1, 2, 3};
int *ptr = arr;                   // Pointer points to first element of array
ptr++;                            // Valid
arr++;                            // Invalid: array name is not a modifiable lvalue

42. How are strings represented in C?

Answer:

In C, strings are arrays of characters terminated by a null character (\0).

 Example

char str1[] = "Hello";                 // Automatically includes '\0'
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

 Important Notes:

  • Stored in contiguous memory.
  • Can be manipulated using standard string functions from <string.h>.

43. How do you pass arrays to functions?

Answer:

In C, arrays are passed to functions by passing the pointer to the first element.

 Function Declaration Example

void printArray(int arr[], int size);
void printArray(int *arr, int size);  // Same as above

 Function Call Example

int nums[] = {1, 2, 3};
printArray(nums, 3);

Inside the function, you can use pointer arithmetic or array indexing to access elements.

44. What are the common string manipulation functions in C?

Answer:

These functions are declared in the <string.h> header:

FunctionDescription
strlen()Returns the length of a string
strcpy()Copies one string to another
strcat()Concatenates two strings
strcmp()Compares two strings
strchr()Finds the first occurrence of a character
strstr()Finds a substring
strncpy()Safer version of strcpy

Example

char str1[20] = "Learn";
char str2[] = "C";
strcat(str1, str2);  // str1 = "LearnC"

45. What are dangling pointers?

Answer:

A dangling pointer is a pointer that points to a memory location that has been freed or is no longer valid.

 Scenarios Causing Dangling Pointers:

         1. Freeing dynamically allocated memory:

int *p = malloc(sizeof(int));
free(p);              // p is now dangling
*p = 10;              // Undefined behavior

     2. Returning address of a local variable:

int* getPtr() {
    int x = 10;
    return &x;        // x is destroyed after function returns
}

 Solution: Always set pointer to NULL after freeing or avoid returning local addresses.

46. What is pointer arithmetic?

Answer:

Pointer arithmetic refers to operations performed on pointers like incrementing, decrementing, adding or subtracting integers.

OperationMeaning
ptr++ / ptr–Moves pointer forward/backward by size of the type
ptr + nMoves pointer forward by n elements
ptr – nMoves pointer backward by n elements

 Example

int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
printf("%d\n", *(p + 2));  // Output: 30

47. What is a null pointer?

Answer:

A null pointer is a pointer that does not point to any valid memory location.

  • Declared using NULL macro from <stddef.h> or <stdio.h>.

 Example

int *ptr = NULL;
if (ptr == NULL) {
    printf("Pointer is null\n");
}

 Usage:

  • Initialize unused pointers.
  • Check pointer validity before dereferencing.
  • Prevents dangling or wild pointer errors.

48. What is the difference between char *str and char str[]?

Answer:

Featurechar *strchar str[]
MemoryPointer to a string literal or heapArray stored in stack memory
ModifiableMay be unmodifiable (if string literal)Modifiable (if local array)
DeclarationPointer to a characterArray of characters

Examples

char *str1 = "Hello";         // Stored in read-only memory (literal)
char str2[] = "Hello";    // Stored in stack, modifiable
str1[0] = 'h';             // Undefined behavior (if literal)
str2[0] = 'h';            // Allowed

49. What is a pointer to pointer?

Answer:

A pointer to pointer (or double pointer) is a pointer that stores the address of another pointer.

 Syntax

int **pp;

Example

int x = 10;
int *p = &x;
int **pp = &p;
printf("%d\n", **pp);  // Output: 10

 Usage:

  • Dynamic 2D arrays
  • Function arguments that modify pointer values
  • Linked structures (e.g., pointers to nodes)

50. How do you allocate and free memory using pointers?

Answer:

C provides dynamic memory management through standard library functions:

FunctionPurpose
malloc()Allocates memory (uninitialized)
calloc()Allocates and initializes memory to 0
realloc()Reallocates memory
free()Frees allocated memory

Declared in <stdlib.h>.

 Example

int *arr = (int*) malloc(5 * sizeof(int));  // Allocate memory for 5 ints
if (arr == NULL) {
    printf("Memory allocation failed\n");
}
// Use memory
arr[0] = 10;
// Free memory
free(arr);
arr = NULL;  // Avoid dangling pointer

 Best Practices:

  • Always check if malloc() returns NULL.
  • Always free() dynamically allocated memory.
  • Set pointer to NULL after freeing.

51. What is the difference between malloc(), calloc(), realloc(), and free()?

Answer:

FunctionDescriptionInitializationSyntax Example
malloc()Allocates memory blockNo (garbage values)int *p = (int*) malloc(5 * sizeof(int));
calloc()Allocates and initializes memoryYes (sets to 0)int *p = (int*) calloc(5, sizeof(int));
realloc()Resizes previously allocated memoryRetains old valuesp = realloc(p, 10 * sizeof(int));
free()Frees allocated memoryN/Afree(p);

 

52. How is memory leakage detected in C?

Answer:

Memory leak occurs when dynamically allocated memory is not freed, causing wasted memory.

 Detection Methods:

  1. Manual Tracking: Check if every malloc()/calloc() has a corresponding free().
  2. Tools  
    • Valgrind (Linux):

valgrind ./your_program

    • AddressSanitizer (GCC/Clang):

Compile with -fsanitize=address

  1. Static Code Analysis Tools:
    • Clang Static Analyzer
    • Cppcheck

53. What is the difference between stack and heap memory?

Answer:

FeatureStackHeap
AllocationAutomatically by compilerManually using malloc() / calloc()
LifetimeEnds when function returnsRemains until explicitly freed
SpeedFasterSlower
SizeLimitedLarge (limited by system RAM)
AccessLIFO (Last In, First Out)Random

 Example

// Stack allocation
int x = 10;
// Heap allocation
int *p = (int*) malloc(sizeof(int));

54.What are file handling functions in C?

Answer:

C provides standard I/O functions in the <stdio.h> library for file operations.

FunctionPurpose
fopen()Opens a file
fclose()Closes an open file
fread()Reads from a file (binary)
fwrite()Writes to a file (binary)
fgetc()Reads a single character
fputc()Writes a single character
fgets()Reads a string
fputs()Writes a string
fprintf()Writes formatted output
fscanf()Reads formatted input
fseek()Moves file pointer to a position
ftell()Tells current position of file ptr

55. What is the difference between text mode and binary mode in file handling?

Answer:

ModeText ModeBinary Mode
Opening Mode“r”, “w”, “a”“rb”, “wb”, “ab”
Data FormatCharacters and readable textRaw bytes (as-is)
Line EndingsTranslated (\n ↔ platform-specific)Not translated
Use CaseLogs, config files, readable dataImages, videos, executables

Example

fopen("file.txt", "r");             // text mode
fopen("image.png", "rb");       // binary mode

56.How do you read/write a file in C?

Answer:

Write Example

FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
    fprintf(fp, "Hello, World!\n");
    fclose(fp);
}

 Read Example

FILE *fp = fopen("data.txt", "r");
char buffer[100];
if (fp != NULL) {
    fgets(buffer, 100, fp);
    printf("Read: %s", buffer);
    fclose(fp);
}

Always check if fopen() returns NULL before proceeding.

57. What is fseek() and ftell() used for?

Answer:

fseek(FILE *stream, long offset, int origin): Moves the file pointer to a specified location.

OriginMeaning
SEEK_SETFrom beginning of file
SEEK_CURFrom current file position
SEEK_ENDFrom end of file

 ftell(FILE *stream): Returns current position of file pointer.

 Example

FILE *fp = fopen("sample.txt", "r");
fseek(fp, 5, SEEK_SET);           // Move to 5th byte
long pos = ftell(fp);             // pos = 5
fclose(fp);

58. What is the difference between fprintf() and fputs()?

Answer:

FunctionDescriptionFormatting Support
fprintf()Writes formatted outputYes (%d, %s, etc.)
fputs()Writes string onlyNo formatting

 Example

fprintf(fp, "ID: %d, Name: %s\n", id, name);
fputs("Simple Line\n", fp);

fprintf() is preferred when you need formatting.

59. How to append data to an existing file in C?

Answer:

Use “a” (text mode) or “ab” (binary mode) with fopen() to append data without erasing existing content.

 Example

FILE *fp = fopen("log.txt", "a");
if (fp != NULL) {
    fputs("New log entry\n", fp);
    fclose(fp);
}

Data is written at the end of the file automatically.

60. How can you handle errors during file operations?

Answer:

Best Practices for File Error Handling:

         1. Check if file is opened successfully:

FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    perror("Error opening file");  // descriptive error
    return 1;
}

       2. Check return values of file functions:

if (fwrite(data, 1, size, fp) != size) {
    fprintf(stderr, "Write error\n");
}

     3. Use ferror() to check stream errors:

if (ferror(fp)) {
    printf("I/O error occurred\n");
}

    4. Close all files using fclose() to release resources.

Note: The interview questions and answers provided on this page have been thoughtfully compiled by our academic team. However, as the content is manually created, there may be occasional errors or omissions. If you have any questions or identify any inaccuracies, please contact us at team@learn2earnlabs.com. We appreciate your feedback and strive for continuous improvement.