C Programming Tricky Questions
Tricky Questions on Static and Dynamic Memory
What is the difference between stack and heap memory?
Stack memory is used for static memory allocation (local variables, function calls). Heap memory is used for dynamic memory allocation (malloc, calloc, realloc). Stack is faster but limited in size, heap is slower but larger and flexible.
What is the difference between malloc() and calloc()?
malloc() allocates memory without initializing (contains garbage values). calloc() allocates and initializes all bytes to zero. calloc() also takes two arguments (number of elements, element size) while malloc() takes total bytes.
Tricky Point: calloc() may be slower due to zero initialization, but safer as it avoids garbage values.
What happens if you don't free dynamically allocated memory?
Memory leak occurs - allocated memory remains reserved but inaccessible. Over time, this can exhaust available memory, causing program or system slowdown/crash. Memory is only freed when program terminates.
What is the difference between static and automatic storage duration?
Static variables exist for program lifetime, initialized once. Automatic (local) variables exist only during block execution, created/destroyed with each function call. Static variables retain values between calls.
What is memory fragmentation and what causes it?
Fragmentation occurs when free memory is divided into small, non-contiguous blocks. Caused by frequent allocation/deallocation of varying sizes. Reduces available contiguous memory, though total free memory may be sufficient.
What is the purpose of realloc() and what are its pitfalls?
realloc() resizes previously allocated memory. Pitfalls: may move memory to new location (invalidating old pointers), returns NULL on failure (but original memory remains allocated), size 0 may free memory or allocate zero bytes.
What is a memory pool and why is it used?
Memory pool pre-allocates blocks of memory, then manages allocation/deallocation from this pool. Benefits: reduces fragmentation, faster allocation, predictable memory usage. Used in real-time and embedded systems.
What is the difference between static local and static global variables?
Static local: visible only within function, persists between calls. Static global: visible only within file where defined, persists for program lifetime. Both have static storage duration but different scope.
What happens when you free() a NULL pointer?
free(NULL) does nothing - it's safe to call. This allows writing defensive code that can free pointers without checking for NULL first. However, free() on already freed pointer (double free) causes undefined behavior.
What is the difference between internal and external fragmentation?
Internal fragmentation: wasted memory within allocated block (allocated more than needed). External fragmentation: free memory scattered in small pieces between allocated blocks. Both reduce usable memory.
What is a memory leak detector and how does it work?
Tools like Valgrind track memory allocations and deallocations. They report leaks by comparing allocated vs freed memory. Some work by overriding malloc/free functions to add tracking.
What is the lifetime of dynamically allocated memory?
Dynamically allocated memory exists from malloc/calloc/realloc until explicitly freed with free() or program termination. Unlike stack variables, not tied to scope - programmer must manage lifetime manually.
What is a dangling pointer in context of dynamic memory?
Dangling pointer points to memory that has been freed. Created by: accessing memory after free(), using pointer from realloc() that moved memory, or multiple pointers to same freed memory.
Warning: Using dangling pointers causes undefined behavior - crash, data corruption, or security vulnerabilities.
What is the difference between static and dynamic linking?
Static linking includes library code in executable at compile time. Dynamic linking loads libraries at runtime. Static: larger executables but faster startup. Dynamic: smaller executables, shared libraries, but dependency issues.
What is memory alignment and why is it important?
Alignment ensures data is stored at addresses divisible by its size. Important for performance (CPU reads aligned data faster) and correctness (some architectures require alignment). malloc() returns properly aligned memory.
What is the difference between heap and free store?
In C, "heap" typically refers to memory managed by malloc/free. In C++, "free store" is for new/delete. They're often the same pool but managed differently. Some implementations separate them.
What is garbage collection and does C have it?
Garbage collection automatically reclaims unused memory. C does NOT have built-in garbage collection - programmer must manually free memory. Some third-party libraries add GC to C.
What is the memory layout of a C program?
Typically: text/code segment (executable code), data segment (global/static variables), heap (dynamic memory), stack (local variables, function calls). Each has different properties and lifetime.
What is a memory allocator and what algorithms exist?
Memory allocator manages heap memory. Common algorithms: first-fit, best-fit, worst-fit, buddy system. Each has trade-offs for speed, fragmentation, and memory utilization.
What is the difference between static and dynamic arrays?
Static arrays: size fixed at compile time, stack memory. Dynamic arrays: size determined at runtime, heap memory. Dynamic arrays use malloc/realloc, must be manually freed.
What is a memory overrun/underrun?
Overrun: writing past allocated memory (buffer overflow). Underrun: writing before allocated memory. Both corrupt adjacent memory, causing undefined behavior, crashes, or security vulnerabilities.
What is the difference between brk() and mmap() for memory allocation?
brk() adjusts program break (end of data segment) for small allocations. mmap() maps files/devices into memory, used for large allocations. malloc() may use either internally.
What is the maximum size that can be allocated with malloc()?
Limited by available memory (physical + swap), address space (32-bit: ~4GB, 64-bit: much larger), and OS limits. Very large allocations may fail due to fragmentation even if total memory available.
What is the difference between memory allocation in C and C++?
C uses malloc/calloc/realloc/free (returns void*, no constructors/destructors). C++ uses new/delete (returns typed pointer, calls constructors/destructors). Mixing them causes undefined behavior.
What is smart pointer in C++ and can it be implemented in C?
Smart pointers automatically manage memory (RAII). C doesn't have built-in smart pointers, but can implement similar patterns using structs with cleanup functions. Requires discipline and careful design.
Tricky Point: While C lacks RAII, you can use goto cleanup patterns or custom destructor functions to simulate resource management.
Note: These tricky questions cover important concepts about static and dynamic memory management in C, including allocation strategies, memory safety, performance considerations, and common pitfalls. Understanding memory management is crucial for writing efficient and robust C programs.