*** 1. Explain memory layout of a C program

The memory layout of a C program defines how memory is organized during program execution.


Main Memory Sections

---------------------
| Stack |
---------------------
| Heap |
---------------------
| BSS |
---------------------
| Data |
---------------------
| Text |
---------------------

Sections Overview

SectionPurpose
TextStores program instructions
DataInitialized global/static variables
BSSUninitialized global/static variables
HeapDynamic memory allocation
StackFunction calls and local variables

Example

int global = 10;       // Data section
int uninitialized; // BSS section

int main() {

int local = 5; // Stack

int *p = malloc(sizeof(int)); // Heap
}

Interview Insight

Very common question:

“Which memory grows upward/downward?”

Typically:

  • Heap grows upward
  • Stack grows downward

(Depends on architecture)


*** 2. What are .text, .data, .bss, heap, and stack sections?

1. .text Section

Stores executable instructions (machine code).

Features

  • Read-only
  • Prevents accidental modification

2. .data Section

Stores initialized global and static variables.

Example

int x = 10;

3. .bss Section

Stores uninitialized global and static variables.

Example

int y;

4. Heap Section

Used for dynamic memory allocation.

Functions

malloc()
calloc()
realloc()
free()

5. Stack Section

Stores:

  • Local variables
  • Function calls
  • Return addresses

Features

  • Fast allocation/deallocation
  • Limited size

Key Difference

HeapStack
Manual memory managementAutomatic memory management
SlowerFaster

Interview Insight

Very frequently asked:

“Where are static variables stored?”

Answer:

  • .data section (initialized)
  • .bss section (uninitialized)

*** 3. Difference between static and dynamic memory allocation?

FeatureStatic AllocationDynamic Allocation
Allocation TimeCompile timeRuntime
Memory AreaStack/Data segmentHeap
SizeFixedFlexible
SpeedFasterSlightly slower
Managed ByCompilerProgrammer

Static Allocation Example

int arr[10];

Dynamic Allocation Example

int *arr = (int*) malloc(10 * sizeof(int));

Advantages of Dynamic Allocation

  • Better memory utilization
  • Runtime flexibility

Interview Insight

Common question:

“Which allocation can cause memory leaks?”

Dynamic memory allocation.


** 4. Difference between source code and object code?

FeatureSource CodeObject Code
Written ByProgrammerCompiler
LanguageHigh-level languageMachine-level binary
Extension.c.o or .obj
ReadabilityHuman-readableNot human-readable

Source Code Example

printf("Hello");

Object Code

Generated after compilation.

Contains machine instructions.


Compilation Flow

Source Code -> Object Code -> Executable

Interview Insight

Common question:

“Can object code run directly?”

No. Linking is required to create executable file.


*** 5. Explain compilation stages in C.

C program compilation happens in multiple stages.


Compilation Stages

1. Preprocessing
2. Compilation
3. Assembly
4. Linking

1. Preprocessing

Handles:

  • #include
  • #define
  • Macros

Output

Expanded source code.


2. Compilation

Converts source code into assembly code.

Checks

  • Syntax errors
  • Semantic errors

3. Assembly

Converts assembly code into object code.

Output

.o file

4. Linking

Combines:

  • Object files
  • Library files

Creates executable file.


Complete Flow

.c -> .i -> .s -> .o -> executable

Interview Insight

Very common question:

“At which stage are macros expanded?”

Answer:
Preprocessing stage.


** 6. What is linker and loader?

Linker

Linker combines:

  • Object files
  • Library files

to create executable program.


Responsibilities

  • Resolves external symbols
  • Combines multiple object files

Loader

Loader loads executable into memory for execution.


Responsibilities

  • Allocates memory
  • Loads program into RAM
  • Starts execution

Flow

Compiler -> Linker -> Executable -> Loader -> Memory

Interview Insight

Common question:

“What happens if linker cannot find function definition?”

Linker error occurs:

Undefined reference

*** 7. What is undefined behavior?

Undefined behavior means the C language does not define what should happen.

Program may:

  • Crash
  • Produce incorrect output
  • Work differently on different systems

Example

int x = 5;

printf("%d", x++);

Complex undefined cases:

x = x++;

Common Causes

  • Accessing invalid memory
  • Buffer overflow
  • Dereferencing NULL pointer
  • Modifying variable multiple times without sequence point

Interview Insight

Very important concept in system programming interviews.

Common question:

“Why is undefined behavior dangerous?”

Because compiler behavior becomes unpredictable.


** 8. What is implementation-defined behavior?

Implementation-defined behavior means compiler must choose a behavior and document it.

Different compilers may behave differently.


Example

sizeof(int)

may vary across systems.


Other Examples

  • Signed integer representation
  • Integer size
  • Bit shifting behavior

Key Difference

Undefined BehaviorImplementation-Defined Behavior
No rulesCompiler-defined rules
Completely unpredictablePredictable per compiler

Interview Insight

Frequently confused with undefined behavior.


*** 9. Why is gets() dangerous?

gets() is dangerous because it does not check input size.

This can cause:

Buffer Overflow

Example

char name[10];

gets(name);

If user enters more than 9 characters:

  • Memory corruption occurs
  • Program may crash

Security Risk

Buffer overflow vulnerabilities can lead to:

  • Data corruption
  • Hacking attacks
  • Code injection

Important Point

gets() was removed from:

C11 standard

Interview Insight

Very frequently asked security-related question.


*** 10. Alternative to gets()?

The safest alternative is:

fgets()

Syntax

fgets(str, size, stdin);

Example

char name[20];

fgets(name, sizeof(name), stdin);

Why Safer?

Because it limits number of input characters.


Advantages

  • Prevents buffer overflow
  • Safer input handling

Important Difference

gets()fgets()
UnsafeSafe
No boundary checkBoundary check present

Interview Insight

Common follow-up:

“Does fgets() store newline character?”

Yes, if space is available in buffer.

** 11. What are wild pointers?

A wild pointer is a pointer that has not been initialized properly.

It points to an unknown memory location.


Example

int *p;

Here, p is a wild pointer because it contains garbage address.


Dangerous Because

Using wild pointers may cause:

  • Segmentation fault
  • Undefined behavior
  • Memory corruption

Incorrect Usage

int *p;

*p = 10;

Safe Practice

Initialize pointers:

int *p = NULL;

Interview Insight

Common question:

“Difference between wild pointer and dangling pointer?”

Wild PointerDangling Pointer
UninitializedPoints to freed memory

** 12. What are void pointers?

A void pointer is a generic pointer that can store address of any data type.

Also called:

Generic Pointer

Syntax

void *ptr;

Example

int x = 10;

void *ptr = &x;

Important Point

Void pointers cannot be dereferenced directly.

Need typecasting.


Correct Dereferencing

printf("%d", *(int*)ptr);

Uses

  • Dynamic memory functions
  • Generic data handling
  • Library functions

Interview Insight

Very common question:

“Why does malloc() return void pointer?”

Because it can allocate memory for any data type.


*** 13. Difference between const int *ptr, int * const ptr, and const int * const ptr?

These declarations control:

  • Whether data can change
  • Whether pointer can change

1. const int *ptr

Pointer to constant integer.


Meaning

  • Value cannot change
  • Pointer can change

Example

const int *ptr;

Invalid

*ptr = 10;

Valid

ptr = &x;

2. int * const ptr

Constant pointer to integer.


Meaning

  • Value can change
  • Pointer cannot change

Example

int * const ptr = &x;

Valid

*ptr = 20;

Invalid

ptr = &y;

3. const int * const ptr

Constant pointer to constant integer.


Meaning

  • Value cannot change
  • Pointer cannot change

Example

const int * const ptr = &x;

Invalid

*ptr = 10;
ptr = &y;

Both invalid.


Quick Trick

Read declaration from right to left.

Interview Insight

Very frequently asked pointer interview question.


*** 14. What are function pointers?

A function pointer stores the address of a function.


Why Useful?

Allows:

  • Callback functions
  • Dynamic function calls
  • Runtime behavior selection

Example Function

int add(int a, int b) {
return a + b;
}

Function Pointer Declaration

int (*ptr)(int, int);

Assign Function Address

ptr = add;

Call Function

ptr(2, 3);

Interview Insight

Used heavily in:

  • Operating systems
  • Embedded systems
  • Callback mechanisms

*** 15. How to declare and use function pointers?


Step 1: Create Function

int multiply(int a, int b) {
return a * b;
}

Step 2: Declare Function Pointer

int (*funcPtr)(int, int);

Step 3: Assign Address

funcPtr = multiply;

Step 4: Call Function

printf("%d", funcPtr(2, 3));

Complete Program

#include <stdio.h>

int multiply(int a, int b) {
return a * b;
}

int main() {

int (*funcPtr)(int, int);

funcPtr = multiply;

printf("%d", funcPtr(2, 3));

return 0;
}

Output

6

Interview Insight

Common question:

“Can function pointers point to multiple functions?”

Yes, by changing assigned function address.


*** 16. Explain segmentation fault (SIGSEGV).

A segmentation fault occurs when program accesses invalid memory.

Operating system sends:

SIGSEGV

signal to terminate program.


Example

int *p = NULL;

*p = 10;

Why Happens?

Program tries to access restricted memory.


Common Symptoms

  • Program crash
  • Core dump
  • Runtime termination

Interview Insight

Very important debugging interview topic.


*** 17. Common causes of segmentation fault?

Main Causes

1. Dereferencing NULL Pointer

int *p = NULL;
*p = 5;

2. Accessing Freed Memory

free(p);
*p = 10;

3. Buffer Overflow

char str[5];
gets(str);

4. Stack Overflow

Infinite recursion.


5. Accessing Invalid Array Index

arr[1000]

Prevention

  • Initialize pointers
  • Check bounds
  • Validate memory allocation

Interview Insight

Very common follow-up:

“How to debug segmentation fault?”

Using:

  • gdb
  • Valgrind
  • AddressSanitizer

*** 18. Accessing memory after free().

Accessing memory after free() is called causes undefined behavior.

This is called:

Use-After-Free

Example

int *p = malloc(sizeof(int));

free(p);

*p = 10;

Problems

  • Program crash
  • Data corruption
  • Security vulnerabilities

Safe Practice

After freeing:

p = NULL;

Interview Insight

Use-after-free bugs are common in:

  • System software
  • Embedded programming
  • Security vulnerabilities

*** 19. What happens if malloc() fails?

If malloc() fails, it returns:

NULL

Example

int *p = malloc(1000000000);

if(p == NULL) {
printf("Memory Allocation Failed");
}

Why Failure Happens?

  • Insufficient memory
  • Memory fragmentation
  • System limits

Important Practice

Always check:

if(ptr == NULL)

after allocation.


Interview Insight

Very common interview question:

“What happens if NULL check is skipped?”

Dereferencing NULL may cause segmentation fault.


*** 20. What happens with malloc(0)?

Behavior of:

malloc(0)

is implementation-defined.


Possible Outcomes

1. Returns NULL

or

2. Returns unique valid pointer


Important Point

Returned pointer should not be dereferenced.


Example

int *p = malloc(0);

Safe Practice

Always allocate positive memory size.


Interview Insight

Very tricky interview question.

** 21. Explain heap fragmentation.

Heap fragmentation happens when free memory in heap becomes divided into small scattered blocks.

This makes memory allocation inefficient.


Why It Happens?

Repeated:

  • malloc()
  • free()

operations of different sizes create gaps in memory.


Example

Allocated:
[A][B][C][D]

After freeing B and D:
[A][ ][C][ ]

Now free memory exists, but in fragmented form.


Types of Fragmentation

1. External Fragmentation

Free memory exists but not in contiguous block.

2. Internal Fragmentation

Allocated block contains unused space.


Problems

  • Memory wastage
  • Allocation failure
  • Reduced performance

Prevention

  • Memory pooling
  • Proper allocation strategy
  • Compact memory usage

Interview Insight

Very important concept in:

  • Operating systems
  • Embedded systems
  • Memory management interviews

*** 22. Explain pointer increment behavior.

When a pointer is incremented, it moves by:

size of its data type

not by 1 byte.


Example

int arr[] = {10, 20, 30};

int *p = arr;

p++;

Behavior

If integer size is 4 bytes:

Before increment -> 1000
After increment -> 1004

Character Pointer Example

char *c;
c++;

Moves by:

1 byte

Important Rule

Pointer TypeIncrement Size
char*1 byte
int*4 bytes (usually)
double*8 bytes (usually)

Interview Insight

Very frequently asked pointer question.


*** 23. Remove duplicates in array

This program removes duplicate elements from array.


Program

#include <stdio.h>

int main() {

int arr[] = {1, 2, 2, 3, 4, 4, 5};

int size = 7;

for(int i = 0; i < size; i++) {

for(int j = i + 1; j < size; ) {

if(arr[i] == arr[j]) {

for(int k = j; k < size - 1; k++) {
arr[k] = arr[k + 1];
}

size--;

} else {
j++;
}
}
}

for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Output

1 2 3 4 5

Time Complexity

O(n²)

Interview Insight

Optimization:
Use hashing for:

O(n)

solution.


** 24. Detect unique characters in string

This program checks whether all characters are unique.


Program

#include <stdio.h>
#include <string.h>

int main() {

char str[] = "hello";

int unique = 1;

for(int i = 0; str[i] != '\0'; i++) {

for(int j = i + 1; str[j] != '\0'; j++) {

if(str[i] == str[j]) {
unique = 0;
break;
}
}
}

if(unique)
printf("Unique Characters");
else
printf("Duplicates Found");

return 0;
}

Output

Duplicates Found

Better Approach

Use frequency array or hash set.


Interview Insight

Common interview follow-up:

“How to solve in O(n)?”

Using hashing.


*** 25. Reverse each word in sentence

This program reverses every word individually.


Example

Input:

Hello World

Output:

olleH dlroW

Program

#include <stdio.h>
#include <string.h>

void reverse(char str[], int start, int end) {

while(start < end) {

char temp = str[start];
str[start] = str[end];
str[end] = temp;

start++;
end--;
}
}

int main() {

char str[] = "Hello World";

int start = 0;

for(int i = 0; ; i++) {

if(str[i] == ' ' || str[i] == '\0') {

reverse(str, start, i - 1);

start = i + 1;
}

if(str[i] == '\0')
break;
}

printf("%s", str);

return 0;
}

Interview Insight

Frequently asked string manipulation problem.


** 26. Count subarrays with even sum

A subarray has even sum when:

sum % 2 == 0

Optimized Logic

  • Even + Even = Even
  • Odd + Odd = Even

Program

#include <stdio.h>

int main() {

int arr[] = {1, 2, 3, 4};

int n = 4;

int evenCount = 1;
int oddCount = 0;

int sum = 0;
int result = 0;

for(int i = 0; i < n; i++) {

sum += arr[i];

if(sum % 2 == 0) {

result += evenCount;
evenCount++;

} else {

result += oddCount;
oddCount++;
}
}

printf("%d", result);

return 0;
}

Time Complexity

O(n)

Interview Insight

Important prefix-sum interview problem.


*** 27. Find intersection point of linked lists

Two linked lists intersect if they share same node address.


Efficient Approach

Use:

  • Two pointers
  • Length difference adjustment

Logic

  1. Find lengths
  2. Move longer list ahead
  3. Traverse together

Program

struct Node* getIntersection(struct Node* head1,
struct Node* head2) {

while(head1 != head2) {

head1 = (head1 == NULL) ? head2 : head1->next;

head2 = (head2 == NULL) ? head1 : head2->next;
}

return head1;
}

Time Complexity

O(n)

Interview Insight

Very popular linked-list interview problem.


*** 28. Merge two sorted linked lists

This program merges two sorted linked lists into one sorted list.


Program

struct Node* merge(struct Node* a, struct Node* b) {

if(a == NULL)
return b;

if(b == NULL)
return a;

struct Node* result = NULL;

if(a->data <= b->data) {

result = a;

result->next = merge(a->next, b);

} else {

result = b;

result->next = merge(a, b->next);
}

return result;
}

Example

List1: 1 -> 3 -> 5
List2: 2 -> 4 -> 6

Output:

1 -> 2 -> 3 -> 4 -> 5 -> 6

Interview Insight

Frequently asked recursion + linked list question.


*** 29. Detect circular linked list

A circular linked list contains a loop.


Best Approach

Use:

Floyd’s Cycle Detection Algorithm

Also called:

Tortoise and Hare Algorithm

Program

int hasCycle(struct Node *head) {

struct Node *slow = head;
struct Node *fast = head;

while(fast && fast->next) {

slow = slow->next;
fast = fast->next->next;

if(slow == fast)
return 1;
}

return 0;
}

Time Complexity

O(n)

Space Complexity

O(1)

Interview Insight

Very common DSA interview question.


*** 30. Balanced parentheses using stack

This problem checks whether brackets are balanced.


Example

Valid

{[()]}

Invalid

{[(])}

Logic

  • Push opening brackets into stack
  • Pop when closing bracket appears
  • Check matching pair

Program

#include <stdio.h>
#include <string.h>

char stack[100];
int top = -1;

void push(char c) {
stack[++top] = c;
}

char pop() {
return stack[top--];
}

int main() {

char str[] = "{[()]}";

int balanced = 1;

for(int i = 0; str[i] != '\0'; i++) {

char ch = str[i];

if(ch == '(' || ch == '{' || ch == '[') {

push(ch);

} else {

if(top == -1) {
balanced = 0;
break;
}

char p = pop();

if((ch == ')' && p != '(') ||
(ch == '}' && p != '{') ||
(ch == ']' && p != '[')) {

balanced = 0;
break;
}
}
}

if(top != -1)
balanced = 0;

if(balanced)
printf("Balanced");
else
printf("Not Balanced");

return 0;
}

Time Complexity

O(n)

Interview Insight

Very frequently asked stack interview problem.

*** 31. Add numbers without +

Addition can be performed using bitwise operators.


Logic

  • XOR (^) gives sum without carry
  • AND (&) gives carry
  • Left shift carry by 1

Repeat until carry becomes 0.


Program

#include <stdio.h>

int add(int a, int b) {

while(b != 0) {

int carry = a & b;

a = a ^ b;

b = carry << 1;
}

return a;
}

int main() {

printf("%d", add(5, 3));

return 0;
}

Output

8

Interview Insight

Very common bit manipulation interview problem.


** 32. Subtract without -

Subtraction can be done using:

  • Two’s complement
  • Bitwise addition logic

Logic

a - b = a + (~b + 1)

Program

#include <stdio.h>

int subtract(int a, int b) {

return a + (~b + 1);
}

int main() {

printf("%d", subtract(10, 3));

return 0;
}

Output

7

Interview Insight

Important concept:

~b + 1

represents two’s complement.


** 33. Multiply by 2 without *

Multiplication by 2 can be done using left shift operator.


Logic

x << 1

means:

x * 2

Program

#include <stdio.h>

int main() {

int x = 7;

printf("%d", x << 1);

return 0;
}

Output

14

Why?

Left shift moves bits left by one position.


Interview Insight

Common extension:

x << n = x * 2ⁿ

*** 34. Check EVEN/ODD without arithmetic operators

Use bitwise AND operator.


Logic

Last bit:
0 -> Even
1 -> Odd

Program

#include <stdio.h>

int main() {

int n = 7;

if(n & 1)
printf("Odd");
else
printf("Even");

return 0;
}

Output

Odd

Why Works?

Binary of odd numbers ends with:

1

Interview Insight

Very frequently asked bitwise interview question.


*** 35. Set, clear, toggle, and check bits

Bit manipulation is widely used in:

  • Embedded systems
  • Competitive programming
  • System programming

1. Set Bit

Logic

num | (1 << pos)

Example

num = num | (1 << 2);

2. Clear Bit

Logic

num & ~(1 << pos)

Example

num = num & ~(1 << 2);

3. Toggle Bit

Logic

num ^ (1 << pos)

Example

num = num ^ (1 << 2);

4. Check Bit

Logic

num & (1 << pos)

Example

if(num & (1 << 2))

Quick Summary

OperationFormula
Setx | (1 << n)
Clearx & ~(1 << n)
Togglex ^ (1 << n)
Checkx & (1 << n)

Interview Insight

Extremely common embedded systems interview topic.


*** 36. What is bit masking?

Bit masking means using bitwise operations to manipulate specific bits.


Why Used?

  • Enable/disable flags
  • Extract bits
  • Permission systems
  • Embedded programming

Example

int mask = 1 << 3;

Check Specific Bit

if(num & mask)

Real-World Example

Permission systems:

Read  = 001
Write = 010
Exec = 100

Interview Insight

Bit masking is heavily used in:

  • Device drivers
  • Networking
  • Operating systems

** 37. Difference between signed and unsigned shift

Signed Shift

Works on signed integers.

Right shift may preserve sign bit.


Example

int x = -8;

x >> 1;

Unsigned Shift

Works on unsigned integers.

Vacated bits filled with:

0

Example

unsigned int x = 8;

x >> 1;

Key Difference

FeatureSigned ShiftUnsigned Shift
Sign PreservationYesNo
Fill BitsSign bit0

Interview Insight

Right shift behavior for signed integers can be implementation-defined.


*** 38. Swap numbers without temp variable


Method 1: Using XOR

Program

#include <stdio.h>

int main() {

int a = 5, b = 10;

a = a ^ b;
b = a ^ b;
a = a ^ b;

printf("%d %d", a, b);

return 0;
}

Output

10 5

Method 2: Using Addition/Subtraction

a = a + b;
b = a - b;
a = a - b;

Interview Insight

XOR swap is famous interview question, but temporary variable method is usually more readable.


*** 39. Detect system endianness

Endianness defines byte order in memory.


Types

TypeStorage Order
Little EndianLeast significant byte first
Big EndianMost significant byte first

Program

#include <stdio.h>

int main() {

unsigned int x = 1;

char *c = (char*)&x;

if(*c)
printf("Little Endian");
else
printf("Big Endian");

return 0;
}

Logic

If first byte contains:

1

system is little-endian.


Interview Insight

Very common system programming interview question.


** 40. What is dynamic data structure?

A dynamic data structure can grow or shrink during runtime.

Memory is allocated dynamically using heap memory.


Examples

  • Linked List
  • Stack using linked list
  • Queue
  • Tree
  • Graph

Advantages

  • Flexible size
  • Efficient memory usage
  • Runtime scalability

Example

struct Node {
int data;
struct Node *next;
};

Difference from Static Data Structure

StaticDynamic
Fixed sizeFlexible size
Stack memoryHeap memory

Interview Insight

Common interview question:

“Why are linked lists dynamic?”

Because nodes are allocated at runtime using dynamic memory allocation

*** 41. Difference between stack and queue?

Both are linear data structures but follow different insertion/removal rules.


Key Difference

FeatureStackQueue
PrincipleLIFOFIFO
Full FormLast In First OutFirst In First Out
InsertionPushEnqueue
DeletionPopDequeue

Stack Example

Push: 1 2 3

Pop Order:
3 2 1

Queue Example

Insert: 1 2 3

Remove Order:
1 2 3

Real-World Examples

Stack

  • Function calls
  • Undo operation

Queue

  • Printer queue
  • CPU scheduling

Interview Insight

Very common question:

“Which data structure is used for recursion?”

Answer:

Stack

** 42. What is circular linked list?

A circular linked list is a linked list where the last node points back to the first node.


Representation

10 -> 20 -> 30
^ |
|___________|

Structure

struct Node {
int data;
struct Node *next;
};

Features

  • No NULL at end
  • Circular traversal possible

Advantages

  • Efficient memory traversal
  • Useful in scheduling systems

Applications

  • Round Robin Scheduling
  • Multiplayer games
  • Circular buffers

Interview Insight

Common question:

“How do you stop traversal in circular linked list?”

Stop when pointer reaches starting node again.


*** 43. Advantages of linked list over array?

FeatureLinked ListArray
SizeDynamicFixed
Memory AllocationRuntimeCompile time
Insertion/DeletionEasyCostly
Memory UsageEfficientMay waste memory

Main Advantages

1. Dynamic Size

Can grow or shrink during runtime.


2. Efficient Insert/Delete

No shifting required.


3. Better Memory Utilization

Memory allocated only when needed.


Example

Array insertion -> shifting required
Linked list insertion -> pointer adjustment only

Disadvantages

  • Extra memory for pointers
  • Slower random access

Interview Insight

Very frequently asked:

“Why arrays are faster for indexing?”

Because arrays use contiguous memory.


*** 44. Structure padding and alignment

Structure padding is extra memory added by compiler to align data efficiently.


Why Padding Happens?

To improve:

  • CPU performance
  • Memory access speed

Example

struct Test {
char c;
int x;
};

Expected Size

1 + 4 = 5 bytes

Actual size may become:

8 bytes

due to padding.


Alignment

Compiler aligns variables according to data type boundaries.


Memory Layout Example

char c   -> 1 byte
padding -> 3 bytes
int x -> 4 bytes

Interview Insight

Very common system-level interview topic.


** 45. How to control structure padding?

Padding can be controlled using compiler directives.


Example

#pragma pack(1)

Program

#pragma pack(1)

struct Test {
char c;
int x;
};

Effect

Removes extra padding bytes.


Important Note

Packed structures may reduce performance because of unaligned access.


Alternative

Rearrange members.

Better Layout

struct Test {
int x;
char c;
};

Interview Insight

Common question:

“Why should excessive packing be avoided?”

Because unaligned memory access can slow CPU performance.


** 46. What are bit-fields?

Bit-fields allow variables to use specific number of bits instead of full bytes.


Syntax

struct Data {
unsigned int x : 3;
};

Meaning

x uses only:

3 bits

Example

struct Flags {
unsigned int isActive : 1;
unsigned int isAdmin : 1;
};

Advantages

  • Memory optimization
  • Compact data storage

Common Uses

  • Hardware registers
  • Embedded systems
  • Network protocols

Interview Insight

Very common embedded systems interview topic.


*** 47. Difference between text and binary files?

FeatureText FileBinary File
Storage FormatHuman-readableBinary format
ReadabilityEasyDifficult
SpeedSlowerFaster
SizeLargerSmaller

Text File Example

Hello 123

Binary File Example

Stored in machine binary representation.


Functions

Text File

fprintf()
fscanf()

Binary File

fwrite()
fread()

Interview Insight

Binary files are preferred for:

  • Better performance
  • Compact storage

*** 48. Explain fread() and fwrite().

These functions are used for binary file operations.


1. fwrite()

Writes binary data into file.


Syntax

fwrite(ptr, size, count, fp);

Example

fwrite(&x, sizeof(int), 1, fp);

2. fread()

Reads binary data from file.


Syntax

fread(ptr, size, count, fp);

Example

fread(&x, sizeof(int), 1, fp);

Complete Example

#include <stdio.h>

int main() {

FILE *fp;

int x = 100;

fp = fopen("data.bin", "wb");

fwrite(&x, sizeof(int), 1, fp);

fclose(fp);

return 0;
}

Interview Insight

Very common question:

“Why use binary files?”

Because they are:

  • Faster
  • More compact

*** 49. Read file line-by-line using fgets().

fgets() can read one line at a time from file.


Program

#include <stdio.h>

int main() {

FILE *fp;

char line[100];

fp = fopen("data.txt", "r");

while(fgets(line, sizeof(line), fp)) {

printf("%s", line);
}

fclose(fp);

return 0;
}

How It Works

  • Reads one line
  • Stops at newline or EOF

Advantages

  • Safe input handling
  • Prevents buffer overflow

Interview Insight

Preferred over:

gets()

for safer input handling.


** 50. What is EOF?

EOF stands for:

End Of File

It indicates no more data is available in file.


Value

Usually represented by:

-1

Example

int ch;

while((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}

Why Important?

Used to detect:

  • File end
  • Input completion

Common Functions Using EOF

  • fgetc()
  • scanf()
  • getchar()

Interview Insight

Very common question:

“Why is EOF an int instead of char?”

Because char cannot represent all possible values plus EOF marker.