Bird
Raised Fist0
Cprogramming~20 mins

malloc function - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Malloc Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this malloc usage?
Consider the following C code snippet. What will be printed when it runs?
C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = (int *)malloc(3 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    ptr[0] = 10;
    ptr[1] = 20;
    ptr[2] = 30;
    printf("%d %d %d\n", ptr[0], ptr[1], ptr[2]);
    free(ptr);
    return 0;
}
AGarbage values or segmentation fault
B0 0 0
CMemory allocation failed
D10 20 30
Attempts:
2 left
💡 Hint
Remember that malloc allocates memory but does not initialize it. Here, values are assigned before printing.
❓ Predict Output
intermediate
2:00remaining
What error does this code raise?
What error will this C code produce when run?
C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = malloc(-5 * sizeof(int));
    if (ptr == NULL) {
        printf("Allocation failed\n");
        return 1;
    }
    ptr[0] = 1;
    printf("%d\n", ptr[0]);
    free(ptr);
    return 0;
}
APrints 1 without error
BCompilation error due to negative size
CRuntime error or undefined behavior due to negative size in malloc
DSegmentation fault immediately
Attempts:
2 left
💡 Hint
malloc expects a size_t argument, which is unsigned. Negative values convert to large positive numbers.
🔧 Debug
advanced
2:00remaining
Why does this malloc code cause a memory leak?
Examine the code below. Why does it cause a memory leak?
C
#include <stdlib.h>

int main() {
    int *ptr = malloc(10 * sizeof(int));
    ptr = malloc(20 * sizeof(int));
    free(ptr);
    return 0;
}
AThe first allocated memory is lost because ptr is overwritten before free, causing a leak
BNo memory leak occurs because free is called
Cfree(ptr) is called twice causing a leak
DThe second malloc fails and causes a leak
Attempts:
2 left
💡 Hint
Think about what happens to the pointer after the first malloc before the second malloc.
📝 Syntax
advanced
2:00remaining
Which option causes a compilation error?
Which of the following malloc usages will cause a compilation error?
Aint *p = malloc(5 * sizeof(int)); if (p == NULL) return 1;
Bint *p = malloc(5 * int);
Cint *p = malloc(5 * sizeof(int));
Dint *p = (int *)malloc(5 * sizeof(int));
Attempts:
2 left
💡 Hint
Check the syntax of the sizeof operator in each option.
🚀 Application
expert
2:00remaining
How many integers can be safely stored?
Given this code, how many integers can be safely stored in the allocated memory?
C
#include <stdlib.h>

int main() {
    int *arr = malloc(50 * sizeof(*arr));
    if (!arr) return 1;
    // How many integers can arr hold?
    free(arr);
    return 0;
}
A50 integers
Bsizeof(*arr) integers
C1 integer
DDepends on system architecture
Attempts:
2 left
💡 Hint
malloc allocates memory for 50 times the size of one integer.

Practice

(1/5)
1. What does the malloc function do in C programming?
easy
A. Declares a variable
B. Frees previously allocated memory
C. Allocates a block of memory dynamically during program execution
D. Prints output to the screen

Solution

  1. Step 1: Understand the purpose of malloc

    The malloc function is used to allocate memory dynamically while the program is running, not at compile time.
  2. Step 2: Differentiate malloc from other functions

    Unlike free which releases memory, or printf which outputs text, malloc only allocates memory.
  3. Final Answer:

    Allocates a block of memory dynamically during program execution -> Option C
  4. Quick Check:

    malloc = allocate memory [OK]
Hint: malloc is for getting memory, free is for releasing it [OK]
Common Mistakes:
  • Confusing malloc with free
  • Thinking malloc prints output
  • Assuming malloc declares variables
2. Which of the following is the correct syntax to allocate memory for 10 integers using malloc?
easy
A. int *ptr = malloc(10 * sizeof(int));
B. int *ptr = malloc(10);
C. int ptr = malloc(10 * sizeof(int));
D. int *ptr = malloc(sizeof(int));

Solution

  1. Step 1: Calculate correct size for allocation

    To allocate memory for 10 integers, multiply 10 by the size of an integer using sizeof(int).
  2. Step 2: Use correct pointer type and syntax

    The pointer must be declared as int * and assigned the result of malloc. int *ptr = malloc(10 * sizeof(int)); correctly does this.
  3. Final Answer:

    int *ptr = malloc(10 * sizeof(int)); -> Option A
  4. Quick Check:

    malloc size = count * sizeof(type) [OK]
Hint: Multiply count by sizeof(type) for malloc size [OK]
Common Mistakes:
  • Not multiplying by sizeof(int)
  • Using wrong pointer type
  • Allocating too little memory
3. What will be the output of the following code?
int *p = malloc(4 * sizeof(int));
if (p == NULL) {
    printf("Allocation failed\n");
} else {
    p[0] = 10;
    p[1] = 20;
    printf("%d %d\n", p[0], p[1]);
}
free(p);
medium
A. Compilation error
B. Allocation failed
C. 0 0
D. 10 20

Solution

  1. Step 1: Check if malloc succeeded

    The code checks if p is NULL. If not NULL, allocation succeeded and memory can be used.
  2. Step 2: Assign and print values

    Values 10 and 20 are assigned to p[0] and p[1]. Then they are printed, so output is "10 20".
  3. Final Answer:

    10 20 -> Option D
  4. Quick Check:

    malloc success prints assigned values [OK]
Hint: Check for NULL before using malloc memory [OK]
Common Mistakes:
  • Ignoring NULL check
  • Printing uninitialized memory
  • Forgetting to free memory
4. Identify the error in this code snippet:
char *str = malloc(5);
strcpy(str, "Hello World");
printf("%s", str);
free(str);
medium
A. strcpy is not allowed with malloc
B. malloc size is too small for the string
C. free should be called before strcpy
D. printf format specifier is wrong

Solution

  1. Step 1: Check allocated memory size

    The string "Hello World" needs 12 bytes (11 chars + 1 for '\0'), but only 5 bytes are allocated.
  2. Step 2: Understand consequences of small allocation

    Copying a larger string into smaller allocated memory causes buffer overflow and undefined behavior.
  3. Final Answer:

    malloc size is too small for the string -> Option B
  4. Quick Check:

    Allocate enough memory for string + '\0' [OK]
Hint: Allocate string length + 1 for null terminator [OK]
Common Mistakes:
  • Allocating less memory than string length
  • Calling free before using memory
  • Wrong printf format for strings
5. You want to create a dynamic array of integers that doubles its size when full. Which approach correctly uses malloc and realloc to achieve this?
hard
A. Start with malloc for initial size, then use realloc to double size when needed
B. Use malloc once with maximum size needed upfront
C. Use realloc first, then malloc to allocate memory
D. Use malloc repeatedly without freeing old memory

Solution

  1. Step 1: Allocate initial memory with malloc

    Start by allocating memory for the initial array size using malloc.
  2. Step 2: Use realloc to resize when array is full

    When the array is full, use realloc to double the memory size safely without losing data.
  3. Step 3: Avoid incorrect usage

    Using malloc repeatedly without freeing old memory causes leaks, allocating maximum size upfront wastes memory, and using realloc before malloc is incorrect.
  4. Final Answer:

    Start with malloc for initial size, then use realloc to double size when needed -> Option A
  5. Quick Check:

    malloc first, then realloc to grow [OK]
Hint: malloc once, then realloc to grow array safely [OK]
Common Mistakes:
  • Calling realloc before malloc
  • Allocating max size upfront wasting memory
  • Not freeing old memory causing leaks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard