C Notes
Complete guide to malloc() in C programming — syntax, usage, allocating memory at runtime, checking for NULL, typecasting, practical examples with output, and common mistakes to avoid.
When you declare a variable like int arr[100];, the compiler allocates memory at compile time. But what if you don't know the size until the program is running? That's where malloc() comes in — it lets you request memory from the heap at runtime.
The name malloc stands for memory allocation. It's declared in <stdlib.h> and is the most commonly used function for dynamic memory allocation in C.
Why Do We Need malloc()?
Consider a scenario: you're building a student management system. The number of students varies each semester. You can't hardcode the array size because:
- Too small → buffer overflow and data loss
- Too large → wasted memory
Dynamic allocation with malloc() solves this by letting you request exactly the amount of memory you need, when you need it.
Syntax of malloc()
void *malloc(size_t size);| Parameter | Description |
|---|---|
size | Number of bytes to allocate |
| Return value | Pointer to allocated memory, or NULL on failure |
The function returns a void * (generic pointer), which you must cast to the appropriate type.
How malloc() Works Internally
Key points:
- Memory is allocated on the heap (not the stack)
- The allocated memory contains garbage values (not initialized to zero)
- You must free the memory manually when done
Basic malloc() Example
Dynamic array values: ptr[0] = 10 ptr[1] = 20 ptr[2] = 30 ptr[3] = 40 ptr[4] = 50
Why We Use sizeof() with malloc()
Never hardcode byte sizes. The size of int varies across platforms:
| Platform | sizeof(int) |
|---|---|
| 16-bit systems | 2 bytes |
| 32-bit systems | 4 bytes |
| 64-bit systems | 4 bytes (typically) |
// WRONG - not portable
int *ptr = (int *)malloc(20); // Assumes int is 4 bytes
// CORRECT - portable
int *ptr = (int *)malloc(5 * sizeof(int));Checking for NULL – Critical Step
malloc() returns NULL when the system cannot allocate the requested memory. If you dereference a NULL pointer, your program crashes with a segmentation fault.
Error: Memory allocation failed! Requested too much memory.
Typecasting malloc() – Is It Necessary?
In C, void * is implicitly converted to any other pointer type, so the cast is technically optional:
Best practice: Include the cast for clarity and C++ compatibility.
Practical Example: Dynamic String Input
Enter the length of your name: 10 Enter your name: John Smith Hello, John Smith! (stored in 11 bytes)
malloc() with Structures
ID: 101 Name: Alice Johnson GPA: 3.85
Common Mistakes with malloc()
| Mistake | Consequence | Fix |
|---|---|---|
| Not checking for NULL | Segmentation fault | Always check if (ptr == NULL) |
| Forgetting to free | Memory leak | Call free(ptr) when done |
| Using after free | Undefined behavior | Set ptr = NULL after free |
| Wrong size calculation | Buffer overflow | Use n * sizeof(type) |
| Casting in C++ without cast | Compilation error | Always cast the return |
malloc() vs Stack Allocation
| Feature | malloc() (Heap) | Stack Allocation |
|---|---|---|
| Lifetime | Until free() is called | Until function returns |
| Size | Large (limited by RAM) | Small (typically 1-8 MB) |
| Speed | Slower (OS overhead) | Faster |
| Fragmentation | Possible | None |
| Size known at | Runtime | Compile time |
Interview Questions
Q1: What happens if malloc() fails?
malloc() returns NULL when it cannot allocate the requested memory. You should always check the return value before using the pointer. Dereferencing NULL causes undefined behavior (usually a crash).
Q2: Does malloc() initialize memory to zero?
No. malloc() allocates raw memory containing garbage values. Use calloc() if you need zero-initialized memory, or call memset() after malloc().
**Q3: Why does malloc() return void*?**
Because malloc() is a generic allocator — it doesn't know what type of data you'll store. The void * allows it to be assigned to any pointer type without explicit casting in C.
**Q4: What's the difference between malloc(10) and malloc(10 * sizeof(int))?**
malloc(10) allocates exactly 10 bytes (enough for 10 chars or ~2 ints on a 32-bit system). malloc(10 * sizeof(int)) allocates enough space for 10 integers (typically 40 bytes). Always use sizeof() for portability.
Q5: Can you call malloc() inside a function and return the pointer?
Yes! Since malloc() allocates on the heap, the memory persists after the function returns. The caller is then responsible for calling free() on that pointer.
Summary
malloc()allocates a specified number of bytes from the heap- Always check if the returned pointer is NULL
- Memory is not initialized — it contains garbage values
- Use
sizeof()for portable size calculations - Always
free()allocated memory when you're done - Set pointers to NULL after freeing to avoid dangling pointer bugs
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for malloc() in C – Dynamic Memory Allocation.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, dynamic, memory, allocation, malloc, malloc() in c – dynamic memory allocation
Related C Programming Topics