MCQ on Dynamic Memory Allocation in C — 40 Questions with Answers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Dynamic Memory MCQ, Multiple Choice Questions in C

📑 On this page:
  • Dynamic Memory Basics
  • malloc()
  • calloc()
  • realloc()
  • free() & Memory Leaks
  • Error Handling & Common Bugs
  • Frequently Asked Questions
MCQ on dynamic memory allocation in C including malloc, calloc, realloc, free, memory leaks, and dangling pointers
MCQ on dynamic memory allocation in C — practice set with answers and simple explanations.
📚 In this quiz, you will revise:
  • The four dynamic memory functions: malloc, calloc, realloc, free
  • The return type void* and why NULL checks matter
  • Difference between malloc and calloc (zeroing)
  • Resizing memory blocks safely with realloc
  • Common bugs: memory leaks, double-free, dangling pointers
  • Memory fragmentation and how to avoid it
  • Why free doesn't set the pointer to NULL
  • Best practices for defensive dynamic memory code

This page has 40 multiple choice questions on dynamic memory allocation in C. You'll find questions on malloc, calloc, realloc, and free — what each does, what it returns, and when to use it. You'll also see questions on memory leaks, dangling pointers, double-free bugs, fragmentation, and error handling. Each question comes with the correct answer and a short explanation in plain English, so you understand the "why" and not just the "what". Dynamic memory is heavily tested in interviews and real-world debugging, so mastering these functions pays off in both.

Dynamic Memory Basics

Q1. Which library header must be included to use dynamic memory functions in C?

  • a) <stdlib.h>
  • b) <stdio.h>
  • c) <math.h>
  • d) <memory.h>

Answer: a) <stdlib.h>

malloc, calloc, realloc, and free are all declared in stdlib.h. Without this header, the compiler doesn't know their signatures and may reject your code (or, in old C, silently assume they return int, which truncates pointers — a nasty bug). Include stdlib.h at the top of any file using these functions.

Q2. Which function is used to allocate memory dynamically in C?

  • a) malloc()
  • b) free()
  • c) calloc()
  • d) realloc()

Answer: a) malloc()

malloc (memory allocation) is the primary dynamic allocation function. calloc and realloc are variants, and free releases memory. When asked "the function to allocate", malloc is the canonical answer — it allocates a block of n bytes and returns a void* to it (or NULL). Use it when you need memory whose size is decided at runtime.

Q3. What is the return type of malloc() in C?

  • a) void*
  • b) int
  • c) char
  • d) float

Answer: a) void*

malloc returns void* — a generic pointer to untyped memory. In C, this converts implicitly to any pointer type, so you can write int *p = malloc(...) without a cast. The cast (int *)malloc(...) is optional in C but required in C++. In C, casting is actually discouraged by many style guides because it can hide a missing stdlib.h.

Q4. Where is dynamically allocated memory stored?

  • a) On the stack
  • b) In the data segment
  • c) On the heap
  • d) In CPU registers

Answer: c) On the heap

Dynamic memory lives in the heap — a region of memory managed by malloc and free, separate from the stack. Unlike the stack, the heap grows on demand and persists until you explicitly free it. That's why dynamic memory has program-wide lifetime until freed. Stack is for auto variables, data segment for statics and globals.

Q5. What is the correct syntax to allocate memory for one int in C?

  • a) int *p = malloc(sizeof(int));
  • b) int *p = malloc(int);
  • c) int *p = malloc(sizeof(int*));
  • d) int *p = malloc(size(int));

Answer: a) int *p = malloc(sizeof(int));

malloc takes a byte count, so you must use sizeof(type) to compute the correct size. Option b) passes a type name (not a value), c) allocates a pointer-sized block (wrong for one int on most systems), and d) uses a non-existent "size" function. The idiom malloc(sizeof(T)) or malloc(n * sizeof(T)) appears in nearly every C program that allocates.

Q6. How is memory deallocated in C after dynamically allocating it?

  • a) free()
  • b) delete()
  • c) dealloc()
  • d) release()

Answer: a) free()

free(ptr) releases a block obtained from malloc, calloc, or realloc. It returns the memory to the heap manager for future allocations. delete is a C++ operator — not valid in C. dealloc and release don't exist in C. Every dynamic allocation must be matched by exactly one free.

Q7. Which memory allocation function in C allows resizing of an existing block?

  • a) realloc()
  • b) malloc()
  • c) calloc()
  • d) free()

Answer: a) realloc()

realloc(ptr, newsize) resizes the block pointed to by ptr. It may return the same pointer (in-place resize) or a different one (moved to a larger free region). Always capture the return value — the old pointer becomes invalid after a successful realloc. This is why you should never do ptr = realloc(ptr, newsize) without checking for NULL first.

malloc()

Q8. What happens if malloc fails to allocate memory in C?

  • a) It returns NULL
  • b) It terminates the program
  • c) It returns a random memory address
  • d) It returns a negative value

Answer: a) It returns NULL

malloc returns NULL when it can't satisfy the request (out of memory, block too large, etc.). Dereferencing NULL is undefined behaviour and usually crashes. Always check: if (p == NULL) { perror("malloc"); return 1; }. This is the single most important defensive habit in dynamic memory code.

Q9. Why should you check for NULL after calling malloc()?

  • a) To verify memory was successfully allocated
  • b) To avoid memory leaks
  • c) To deallocate memory
  • d) To initialize the allocated memory

Answer: a) To verify memory was successfully allocated

malloc can fail — returns NULL. Dereferencing NULL leads to crashes or worse (silent corruption on embedded systems). The NULL check is a "did my allocation succeed?" gate. It doesn't prevent leaks (that's free), doesn't deallocate (that's free), and doesn't initialize (malloc doesn't zero memory). It's purely a safety check.

Q10. How is memory alignment maintained for malloc-allocated memory?

  • a) By the user explicitly aligning memory
  • b) By allocating in multiples of 4 bytes only
  • c) By the C library, which returns suitably aligned memory for any type
  • d) Memory is not aligned

Answer: c) By the C library, which returns suitably aligned memory for any type

malloc returns memory aligned for any fundamental type (typically 8 or 16 bytes on modern systems). This means a malloc'd block can safely store an int, a double, a struct, or even a SIMD vector without alignment issues. You don't need to align manually — the allocator does it for you. This is one reason malloc is a bit slower than stack allocation.

Q11. What does malloc(0) return in C?

  • a) NULL always
  • b) A unique non-dereferenceable pointer (or NULL) — implementation-defined
  • c) A crash
  • d) A pointer that can be safely dereferenced

Answer: b) A unique non-dereferenceable pointer (or NULL) — implementation-defined

The C standard says malloc(0) may return NULL, or a unique pointer that can be passed to free but must not be dereferenced. The behaviour is implementation-dependent. Never call malloc(0) in real code — if you don't know the size you need, handle the case explicitly. This is a subtle portability gotcha that comes up in interviews.

Q12. Is casting the return value of malloc() required in C?

  • a) Yes, always
  • b) No — C allows implicit conversion from void*
  • c) Only in C89
  • d) Only for large allocations

Answer: b) No — C allows implicit conversion from void*

In C, void* converts implicitly to any pointer type, so int *p = malloc(...) compiles fine. In C++, casting is required. Many C style guides discourage the cast even though it's legal, because if you forget to #include stdlib.h, the compiler will assume malloc returns int and silently truncate the pointer — the cast hides this bug. Modern linters catch it either way, but the "don't cast in C" rule of thumb remains popular.

calloc()

Q13. What does calloc() do in C?

  • a) Allocates memory and initializes all bytes to zero
  • b) Allocates memory and initializes with random values
  • c) Allocates memory without initialization
  • d) Allocates memory with predefined values

Answer: a) Allocates memory and initializes all bytes to zero

calloc(n, size) allocates n × size bytes and zeroes them out before returning. This is the key difference from malloc — malloc leaves the memory uninitialized (garbage), while calloc gives you clean memory. Use calloc when you need zero-initialized data (like arrays of counters or flags) and don't want to manually memset.

Q14. What is the difference between malloc and calloc in C?

  • a) malloc initializes memory to zero; calloc does not
  • b) calloc allocates memory in multiples of the specified size
  • c) malloc allocates memory and returns a random address
  • d) calloc initializes memory to zero; malloc does not

Answer: d) calloc initializes memory to zero; malloc does not

Both allocate memory from the heap. The key difference: calloc zeroes the memory before returning it (this is guaranteed by the standard), while malloc leaves it uninitialized. calloc is slightly slower because of the zeroing, but safer if you need clean memory. Both return NULL on failure. Option a) has it backwards — a common trick in exam questions.

Q15. What is the correct syntax of calloc() in C?

  • a) void *calloc(size_t nmemb, size_t size);
  • b) void *calloc(size_t size);
  • c) void *calloc(int count, int bytes);
  • d) void *calloc(void *ptr, size_t newsize);

Answer: a) void *calloc(size_t nmemb, size_t size);

calloc takes two arguments: number of elements and size of each element. So calloc(10, sizeof(int)) allocates 10 ints and zero-initializes them. This is different from malloc, which takes one argument (total bytes). Option c) is close but uses int instead of size_t (fine for small values but not standard). Option d) is closer to realloc's signature.

Q16. Which function should be used to allocate a contiguous zeroed array of elements in C?

  • a) malloc()
  • b) calloc()
  • c) realloc()
  • d) free()

Answer: b) calloc()

calloc is the natural choice for array allocation that needs zero initialization. int *arr = calloc(10, sizeof(int)); gives you 10 ints, all 0. You could achieve the same with malloc + memset, but calloc is cleaner and lets the allocator optimize (some allocators return zeroed pages from the OS without extra work). Use malloc only if you'll overwrite the memory immediately anyway.

realloc()

Q17. What is the primary use case for realloc() in C?

  • a) To allocate a new memory block
  • b) To resize an existing memory block
  • c) To free memory after use
  • d) To avoid memory leaks

Answer: b) To resize an existing memory block

realloc(ptr, newsize) is specifically for resizing. Common use case: a dynamic array that grows as you add items. arr = realloc(arr, (n + 1) * sizeof(int)) expands the array by one slot. If newsize is smaller, the block shrinks. If ptr is NULL, realloc acts like malloc. If newsize is 0, behaviour is implementation-defined (often like free).

Q18. Can realloc() reduce the size of a memory block?

  • a) Yes — it can grow or shrink the block
  • b) No — it can only increase the size
  • c) No — it can only grow after being freed
  • d) Only for blocks allocated with calloc

Answer: a) Yes — it can grow or shrink the block

realloc handles both directions. Passing a smaller size truncates the block (the tail is discarded or marked reusable). Passing a larger size grows it, possibly by moving the block to a new location. Many beginners assume realloc only grows — it works both ways. Just remember: on success, the original pointer may be invalid (moved), so update your variable with the return value.

Q19. What happens to the original block if realloc() fails?

  • a) The original block remains unchanged (and realloc returns NULL)
  • b) The program terminates
  • c) The original block is deallocated
  • d) Only the first byte is preserved

Answer: a) The original block remains unchanged (and realloc returns NULL)

This is a critical safety property: if realloc fails (returns NULL), the original block is untouched — you can still use the old pointer. This is why the safe pattern is:
void *newptr = realloc(ptr, newsize);
if (newptr == NULL) { /* handle error, keep old ptr */ }
else { ptr = newptr; }
Never write ptr = realloc(ptr, ...) — if it fails, you lose your original pointer and leak the memory.

Q20. What is the correct way to safely resize a dynamically allocated array in C?

  • a) arr = realloc(arr, newsize);
  • b) realloc(arr, newsize);
  • c) void *tmp = realloc(arr, newsize); if (tmp) arr = tmp;
  • d) free(arr); arr = realloc(arr, newsize);

Answer: c) void *tmp = realloc(arr, newsize); if (tmp) arr = tmp;

This is the safe idiom. Capturing realloc into a temporary means that if it fails (returns NULL), you still have the original arr intact. Option a) leaks the original block on failure, because arr would be overwritten with NULL. Option b) discards the return value, so the resized block is unreachable (leak). Option d) frees the block and then passes a dangling pointer to realloc — undefined behaviour. Option c) is the only safe pattern.

Q21. What does realloc(NULL, size) do in C?

  • a) Crashes
  • b) Behaves like malloc(size)
  • c) Behaves like free(NULL)
  • d) Returns NULL

Answer: b) Behaves like malloc(size)

The C standard explicitly says realloc with a NULL pointer is equivalent to malloc(size). This lets you write a grow-loop that starts with a NULL pointer and calls realloc each time without special-casing the first iteration:
int *arr = NULL;
for (int i = 0; i < n; i++) arr = realloc(arr, (i+1) * sizeof(int));
Note: still capture the return into a temp and check for NULL for safety.

free() & Memory Leaks

Q22. How do you deallocate a dynamically allocated array when it's no longer needed?

  • a) Using the delete operator
  • b) Using free(arr)
  • c) Using realloc(arr, 0)
  • d) By assigning NULL to the pointer

Answer: b) Using free(arr)

free(arr) releases the array back to the heap. delete is C++ only. realloc(arr, 0) is technically implementation-defined and not recommended. Assigning NULL to the pointer only loses the reference — the memory is still allocated (leak). free is the correct answer, always followed by setting arr = NULL to prevent use-after-free.

Q23. What does free() do to the pointer variable after being called?

  • a) It sets the pointer to NULL
  • b) It sets the pointer to 0
  • c) Nothing — the pointer still contains the old address
  • d) It frees the pointer variable itself

Answer: c) Nothing — the pointer still contains the old address

free() releases the memory, but it can't modify the caller's pointer because it receives it by value. The pointer still holds the address of the freed block — that's a dangling pointer. Any subsequent use of it is undefined behaviour. Always set the pointer to NULL after free: free(p); p = NULL;. This is one of the most-asked interview questions in dynamic memory.

Q24. How can memory leaks be avoided in C?

  • a) Always deallocate memory after use
  • b) Avoid dynamic memory entirely
  • c) Ignore them — they're harmless
  • d) Use realloc instead of malloc

Answer: a) Always deallocate memory after use

Every malloc/calloc/realloc must have a matching free. Track every allocation carefully, free it on every code path (including error paths), and consider running Valgrind or AddressSanitizer to catch leaks. Avoiding dynamic memory entirely (option b) isn't realistic for real programs. Ignoring leaks (option c) leads to out-of-memory crashes in long-running programs.

Q25. What happens if you free the same pointer twice?

  • a) The second free is ignored
  • b) Undefined behaviour — may crash or corrupt the heap
  • c) The pointer becomes NULL
  • d) The program exits

Answer: b) Undefined behaviour — may crash or corrupt the heap

Double-free corrupts the allocator's internal bookkeeping, which can crash now or corrupt unrelated allocations later. Some allocators catch double-free (glibc prints an error), but you can't rely on it. Setting the pointer to NULL after free prevents this: free(NULL) is safely a no-op, so a second free on a NULLed pointer does nothing.

Q26. What is a memory leak in C?

  • a) Memory that is read past its bounds
  • b) Memory that is allocated but never freed
  • c) Memory that is used after being freed
  • d) Memory that is written without initialization

Answer: b) Memory that is allocated but never freed

A memory leak is allocated memory that becomes inaccessible because the pointer was lost (overwritten, out of scope, etc.) without being freed. The OS reclaims it when the program exits, but during a long-running program, leaks accumulate and eventually exhaust available memory. Option a) is a buffer overflow, c) is use-after-free, d) is uninitialized read. All four are bugs but different kinds.

Q27. How can memory leaks be identified in C programs?

  • a) By running static analysis tools
  • b) By manually reviewing the code
  • c) By using debuggers like Valgrind
  • d) All of the above

Answer: d) All of the above

There's no single perfect tool, so combine approaches: static analyzers (clang-tidy, cppcheck) catch obvious patterns at compile time; manual review catches logic errors tools miss; and runtime tools (Valgrind, AddressSanitizer, LeakSanitizer) detect leaks that only show up during execution. Real codebases use all three.

Q28. What is a dangling pointer?

  • a) A pointer that points to NULL
  • b) A pointer that has never been initialized
  • c) A pointer to memory that has been freed or gone out of scope
  • d) A pointer with the wrong type

Answer: c) A pointer to memory that has been freed or gone out of scope

Dangling pointers point to memory that no longer belongs to you — either because it was freed or because a local variable went out of scope. Reading or writing through them is undefined behaviour. Prevention: set pointers to NULL after free, never return pointers to local variables, and never use a pointer after its target has been freed.

Q29. How can memory fragmentation be reduced in C?

  • a) By using realloc instead of malloc
  • b) By using calloc instead of malloc
  • c) By freeing memory blocks when they are no longer needed and reusing them efficiently
  • d) By ignoring it — fragmentation is unavoidable

Answer: c) By freeing memory blocks when they are no longer needed and reusing them efficiently

Fragmentation happens when free memory is scattered in small chunks that can't satisfy a large request. Reduce it by: freeing memory promptly (not at program exit), using pools or arenas for same-sized allocations, growing arrays in powers of 2 rather than one at a time, and avoiding mixed sizes of blocks. It's a real problem in long-running servers and embedded systems.

Q30. Why should dynamic memory allocation be used sparingly in C?

  • a) It's faster and more efficient than static memory allocation
  • b) It can lead to memory leaks, fragmentation, and slower performance
  • c) It's easier to manage than static memory allocation
  • d) It always uses less memory

Answer: b) It can lead to memory leaks, fragmentation, and slower performance

Dynamic memory is powerful but comes with costs: allocator overhead (each malloc has bookkeeping), heap fragmentation, potential leaks, and slower access than the stack (because of cache misses). Use stack allocation when the size is known and small; reserve the heap for large or runtime-sized data. Option a) is wrong — malloc is typically slower than auto/stack. Option d) is wrong — dynamic memory uses more (metadata overhead per block).

Error Handling & Common Bugs

Q31. What will the following code do?

int *p = malloc(5 * sizeof(int));
memset(p, 0, 5 * sizeof(int));
  • a) Allocate memory for 5 integers and initialize them to zero
  • b) Allocate memory for 5 integers without initialization
  • c) Initialize an existing array to zero
  • d) Deallocate memory for 5 integers

Answer: a) Allocate memory for 5 integers and initialize them to zero

malloc allocates 5 × sizeof(int) bytes (garbage). Then memset writes zero bytes across the whole block, effectively zero-initializing it. This pattern is exactly what calloc does in one step — which is why "calloc(5, sizeof(int))" is often a cleaner choice than malloc + memset. But the given code does work as long as the malloc succeeded (missing NULL check).

Q32. When using malloc, what should you do before using the allocated memory?

  • a) Initialize the memory with memset
  • b) Check if the allocation was successful (NULL check)
  • c) Deallocate the memory with free
  • d) Cast the return value to the correct type

Answer: b) Check if the allocation was successful (NULL check)

The first thing to do after malloc is check for NULL. If it's NULL, don't use the memory at all — handle the error. Initializing with memset (option a) is optional (depends on whether you need zeroed memory). Casting (option d) is optional in C. Freeing (option c) is the last thing, not the first. The NULL check is non-negotiable.

Q33. What is the purpose of the sizeof operator when calling malloc?

  • a) To determine the number of bytes to allocate
  • b) To check the alignment of memory
  • c) To get the memory address of an allocated block
  • d) To size the memory block being released

Answer: a) To determine the number of bytes to allocate

malloc takes a byte count, so you must compute the size in bytes. sizeof(type) gives the size of one element; multiply by the number you need: malloc(10 * sizeof(int)). This idiom is portable — it works even if int's size varies (2 bytes on some systems, 4 on most). Hardcoding 40 bytes would break on systems where int is not 4 bytes.

Q34. When using dynamic memory allocation in C, how can memory corruption be avoided?

  • a) By using the new operator instead of malloc
  • b) By initializing memory after allocation
  • c) By carefully managing allocation, bounds, and deallocation
  • d) By not using dynamic memory at all

Answer: c) By carefully managing allocation, bounds, and deallocation

Memory corruption comes from: writing past bounds (buffer overflow), using after free, double-free, uninitialized reads, and dangling pointers. Preventing it requires discipline across the whole lifecycle: check allocation, respect bounds, initialize before read, free exactly once, NULL after free. No single trick prevents all corruption — it's a discipline. Tools like AddressSanitizer help catch what you miss.

Q35. What happens if the free() function is called with a NULL pointer?

  • a) The program crashes
  • b) Undefined behaviour
  • c) Nothing happens — free(NULL) is safely a no-op
  • d) The OS frees all memory

Answer: c) Nothing happens — free(NULL) is safely a no-op

The C standard explicitly says free(NULL) has no effect. This is why setting a pointer to NULL after free is such a good habit — accidental double-free becomes a harmless no-op instead of heap corruption. It's one of the few places where C is defensive by default. Make use of it.

Q36. What does the following code return when there is insufficient memory?

int *p = (int *)calloc(1000000, sizeof(int));
  • a) A pointer to uninitialized memory
  • b) NULL
  • c) A garbage pointer value
  • d) The program terminates automatically

Answer: b) NULL

Both calloc and malloc return NULL when allocation fails. This is why you always check — 1,000,000 ints is 4 MB, which is fine on modern systems, but if you were asking for 4 TB, calloc would return NULL and you'd need to handle the error. Without a check, dereferencing NULL is undefined behaviour and usually a crash.

Q37. What is the correct way to use a dynamically allocated struct through a pointer?

  • a) struct Point *p = malloc(sizeof(struct Point)); p->x = 10;
  • b) struct Point p = malloc(sizeof(struct Point)); p.x = 10;
  • c) struct Point *p = malloc(struct Point); p->x = 10;
  • d) struct Point *p = calloc(sizeof(struct Point)); *p.x = 10;

Answer: a) struct Point *p = malloc(sizeof(struct Point)); p->x = 10;

Option a) is the correct pattern: declare a pointer, allocate with sizeof, and access members via the arrow operator. Option b) is wrong — malloc returns a pointer, not a struct value. Option c) passes a type name (not a value) to malloc. Option d) has incorrect sizeof argument (missing sizeof) and *.p.x would parse as *(p.x) which is wrong. The arrow operator p->x is shorthand for (*p).x.

Q38. What does realloc(ptr, 0) do in C?

  • a) Returns NULL and frees ptr
  • b) Implementation-defined — often frees ptr, but don't rely on it
  • c) Allocates a zero-byte block
  • d) Crashes

Answer: b) Implementation-defined — often frees ptr, but don't rely on it

The C standard says behaviour is implementation-defined when realloc is called with size 0. In practice, most implementations free the block and return NULL. But that's not guaranteed, and using the return value after is unsafe. The correct idiom if you want to free is to call free(ptr) explicitly. This is a subtle portability gotcha that catches even experienced programmers.

Q39. What is the most important thing to remember when using malloc/free in a program?

  • a) malloc is faster than stack allocation
  • b) Every allocation must have exactly one matching free on every code path
  • c) Casting is required
  • d) malloc always succeeds

Answer: b) Every allocation must have exactly one matching free on every code path

This rule of thumb prevents most dynamic memory bugs. Every successful malloc, calloc, or realloc must eventually be freed exactly once — including on error paths. Forgetting this is a leak; doing it twice is undefined behaviour. Design functions so that ownership is clear: either the caller owns the returned pointer, or the function frees it internally. A little discipline prevents almost all bugs.

Q40. Which of the following best describes the correct lifecycle of dynamically allocated memory in C?

  • a) malloc → use → free → set pointer to NULL
  • b) malloc → free → use → return
  • c) malloc → free → free again
  • d) use → malloc → free

Answer: a) malloc → use → free → set pointer to NULL

Option a) is the complete safe lifecycle: allocate, use within bounds, free exactly once, and NULL the pointer to prevent accidental reuse. Option b) uses after free (dangling pointer). Option c) is a double-free. Option d) uses memory that hasn't been allocated. Memorize the pattern — it's the single most important takeaway from dynamic memory in C.

Frequently Asked Questions

What is the difference between malloc and calloc in C?

malloc(size) allocates size bytes and leaves the memory uninitialized (garbage). calloc(n, size) allocates n × size bytes and initializes all bytes to zero. calloc is slightly slower because of the zeroing, but safer if you need clean memory. Both return void* (or NULL on failure). Use calloc when you need zeroed memory; use malloc when you'll overwrite it immediately.

Why must I check for NULL after malloc?

malloc returns NULL when it fails (out of memory, oversized request). Dereferencing a NULL pointer is undefined behaviour and usually crashes. Always check the return value before using the pointer — it's the single most important defensive habit in dynamic memory code. Without it, your program may crash at the worst possible moment.

What happens if I call free twice on the same pointer?

Double-free is undefined behaviour — it can crash immediately, silently corrupt the heap, or appear to work until a later crash. Set the pointer to NULL after free; free(NULL) is safely a no-op. This one-line habit prevents most double-free bugs and is worth adopting universally.

Why doesn't free set my pointer to NULL?

free() takes the pointer by value, so it has no way to modify the caller's variable. It only releases the memory. If you want to be safe against use-after-free, set the pointer to NULL yourself after every free call: free(p); p = NULL;. This is a two-line pattern that every C programmer should internalize.

Is it safe to cast the return value of malloc?

In C, casting is unnecessary because void* converts implicitly to any pointer type. It's also discouraged because forgetting to include stdlib.h with a cast hides a real bug (malloc implicitly returns int, which can truncate the pointer). In C++, casting is required. Many C style guides advise against casting. Modern code often skips the cast; either is fine as long as you're consistent.

💡 Tip: Dynamic memory questions are almost always testing the same few ideas: NULL check after allocation, safe realloc idiom (capture return in temp), set pointer to NULL after free, and know the difference between malloc and calloc. If you can write those four patterns from memory, you'll ace almost every dynamic memory question in exams and interviews.

📖 Related MCQ & FAQ Pages

  • Introduction to C MCQ
  • Operators MCQ
  • Conditional Statements MCQ
  • Loops MCQ
  • Arrays MCQ
  • Functions MCQ
  • Structures MCQ
  • Pointers MCQ
  • Files MCQ
  • Storage Classes MCQ

Previous Topic: -->> Storage Classes MCQ   ||   Next topic: -->> More MCQ in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.