Fundamentals 18 min read

Interview Q&A: C Language Basics, Algorithms, Memory Management, and System Programming

This article provides concise explanations and code examples for common interview questions covering C global variable defaults, binary representations, finding top‑k elements, double‑pointer and binary search techniques, OOP concepts in C, differences between C++ class and struct, UDP packet limits, TCP read() return values, memory leaks in infinite loops, and resource cleanup on process exit.

IT Services Circle
IT Services Circle
IT Services Circle
Interview Q&A: C Language Basics, Algorithms, Memory Management, and System Programming

1. Default value of an uninitialized global variable in C

In C, a global variable that is defined without an explicit initializer is automatically initialized to zero. The default value depends on the variable type:

For integer types (int, char, long, etc.) and enum types, the default is 0.

For floating‑point types (float, double, etc.), the default is 0.0.

For pointer types, the default is NULL.

2. Source code, one's complement, and two's complement of -2 and -3

The calculation method is:

Original code: the sign bit of a negative number is the inverse of its absolute value's sign bit.

One's complement: invert all bits except the sign bit for negative numbers.

Two's complement: invert the original code of the absolute value and add 1.

-2 binary representation:

Original code: 1000 0010 One's complement: 1111 1101 Two's complement: 1111 1110 -3 binary representation:

Original code: 1000 0011 One's complement: 1111 1100 Two's complement:

1111 1101

3. Find the top k largest elements in an array of n elements

Method 1: Using a heap

Build a min‑heap containing the first k elements.

Traverse the remaining elements; if an element is larger than the heap top, replace the top and adjust the heap.

After traversal, the heap holds the k largest elements.

Method 2: Using quick‑select (quick sort idea)

Select a pivot, partition the array into elements greater and smaller than the pivot.

If the pivot position equals k, the top k elements are found; otherwise continue the search in the appropriate partition.

Optimizations such as random pivot selection or median‑of‑three can improve efficiency.

4. Explain double‑pointer and binary search algorithms

Double pointer

The double‑pointer technique uses two pointers that start at different positions in an array or linked list and move according to the problem requirements.

Idea

Initialize two pointers, typically at the head and tail (or other suitable positions).

Move the pointers based on the algorithm until they meet or a termination condition is met.

Application scenarios

Two‑sum problem: move pointers to find a pair whose sum equals the target.

Cycle detection in a linked list: fast and slow pointers.

Merging two sorted arrays: compare elements pointed to by each pointer and copy the smaller one.

Binary search

Binary search efficiently finds a target value in a sorted array.

Idea

Set left and right boundary pointers to the start and end of the array.

Compare the middle element with the target; if equal, return the index; if smaller, search the right half; if larger, search the left half.

Repeat until the target is found or the boundaries cross.

Application scenarios

Search in a sorted array (O(log n) time).

Search in a rotated sorted array by first locating the rotation point.

5. Implement encapsulation, inheritance, and polymorphism in C on Linux

Encapsulation

Encapsulation can be simulated with a struct to hold data and functions to operate on that data.

#include <stdio.h>

// Define a struct that encapsulates data
typedef struct {
    int data; // data member
} Encapsulation;

// Function to set data
void setData(Encapsulation *obj, int value) {
    obj->data = value;
}

// Function to get data
int getData(Encapsulation *obj) {
    return obj->data;
}

int main() {
    Encapsulation obj; // create an Encapsulation object
    setData(&obj, 42); // set data to 42
    printf("%d
", getData(&obj)); // print data
    return 0;
}

Inheritance

Inheritance can be mimicked by embedding a parent struct inside a child struct.

#include <stdio.h>

// Parent struct
typedef struct {
    int data; // parent data member
} Parent;

// Child struct that contains the parent struct
typedef struct {
    Parent parent; // embed parent
    int childData; // child‑specific member
} Child;

// Function to set child data
void setChildData(Child *obj, int value) {
    obj->childData = value;
}

int main() {
    Child obj; // create a Child object
    obj.parent.data = 42; // set parent data
    setChildData(&obj, 24); // set child data
    printf("%d %d
", obj.parent.data, obj.childData); // print both
    return 0;
}

Polymorphism

Polymorphism can be achieved with function pointers inside a struct.

#include <stdio.h>

// Struct containing a function pointer for polymorphism
typedef struct {
    int data; // data member
    void (*print)(void *); // function pointer
} Polymorphism;

// Function to print an integer
void printInt(void *obj) {
    printf("%d
", ((Polymorphism *)obj)->data);
}

int main() {
    Polymorphism obj; // create a Polymorphism object
    obj.data = 42; // set data
    obj.print = printInt; // assign function pointer
    obj.print(&obj); // invoke via pointer
    return 0;
}

6. Difference between class and struct in C++

Key differences:

Default member access: class members are private by default, while struct members are public.

Default inheritance access: class inherits privately by default; struct inherits publicly.

Member functions: in a class they are private by default, in a struct they are public.

// C++ class example
class MyClass {
private:
    int privateMember;
public:
    void publicMethod() {
        // can access privateMember
        privateMember = 10;
    }
};

// C struct example
struct MyStruct {
    int publicMember;
private:
    void privateMethod() {
        // cannot be called from outside
    }
public:
    void publicMethod() {
        // can access publicMember
        publicMember = 20;
        // cannot call privateMethod from outside
    }
};

7. Maximum length of a UDP packet

The maximum UDP payload is 65 507 bytes (64 KB − 8 bytes UDP header − 20 bytes IP header). This limit comes from the IPv4/IPv6 total datagram size (65 535 bytes) minus the IP and UDP headers. Network MTU constraints may cause fragmentation.

8. Meaning of a return value of 0 from read in TCP communication

When read returns 0, it indicates that the peer has performed an orderly shutdown; the connection is closed and no more data can be read.

char buffer[1024];
int bytesRead = read(socket_fd, buffer, sizeof(buffer));
if (bytesRead == 0) {
    // Peer has closed the connection
    printf("Peer closed connection
");
    close(socket_fd);
    exit(0);
} else if (bytesRead < 0) {
    // Read error
    perror("read error");
    exit(1);
} else {
    // Process the data
    printf("Read %d bytes
", bytesRead);
    // ...
}

9. Will an infinite while(1) loop that continuously calls malloc cause the program to crash?

Continuously allocating memory without freeing it leads to a memory leak; eventually the process exhausts available memory and crashes.

#include <stdlib.h>

int main() {
    while (1) {
        // Allocate memory repeatedly without freeing
        int *ptr = (int *)malloc(sizeof(int));
        // To avoid leak, free(ptr) should be called when the memory is no longer needed
    }
    return 0;
}

10. How to handle unreleased resources when a process exits

Best practices include:

Explicitly free memory, close file descriptors, and release other resources before exiting.

Register cleanup functions with atexit to perform automatic resource release.

Rely on the operating system’s resource reclamation, though explicit cleanup is preferred.

#include <stdlib.h>

void cleanup() {
    // Code to release resources
}

int main() {
    atexit(cleanup);
    // Other code
    return 0;
}

11‑13. Additional interview questions (project comparison with Google TCMalloc, fragmentation handling, double‑free protection)

These questions require deep knowledge of the specific project and are left unanswered here.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Memory ManagementCOperating SystemsProgramming Interview
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.