0
0
Cprogramming~5 mins

malloc function - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the malloc function do in C?
The malloc function allocates a block of memory of a specified size on the heap and returns a pointer to the beginning of this block.
Click to reveal answer
beginner
What header file must be included to use malloc?
You must include the <stdlib.h> header file to use malloc in C.
Click to reveal answer
beginner
What does malloc return if it fails to allocate memory?
malloc returns NULL if it cannot allocate the requested memory.
Click to reveal answer
beginner
How do you properly free memory allocated by malloc?
You use the free function and pass the pointer returned by malloc to release the allocated memory back to the system.
Click to reveal answer
beginner
Example: What does this code do?<br>
int *p = malloc(5 * sizeof(int));
This code allocates memory for an array of 5 integers on the heap and stores the pointer to this memory in p. The cast to (int *) is not necessary in C and is omitted here.
Click to reveal answer
What is the correct way to allocate memory for 10 doubles using malloc?
Amalloc(10);
Bmalloc(10 * sizeof(int));
Cmalloc(10 * sizeof(double));
Dmalloc(sizeof(double));
If malloc fails, what value does it return?
AGarbage value
B0
C-1
DNULL
Which header file is required to use malloc?
A<code>&lt;stdlib.h&gt;</code>
B<code>&lt;string.h&gt;</code>
C<code>&lt;stdio.h&gt;</code>
D<code>&lt;malloc.h&gt;</code>
What must you do after you finish using memory allocated by malloc?
ANothing, it frees automatically
BCall <code>free</code> with the pointer
CCall <code>delete</code>
DSet pointer to NULL
What type of pointer does malloc return?
Avoid *
Bint *
Cchar *
Dfloat *
Explain how malloc works and why it is important in C programming.
Think about how programs get memory dynamically.
You got /4 concepts.
    Describe the steps to safely allocate and free memory using malloc.
    Consider what happens if malloc fails and how to avoid memory leaks.
    You got /5 concepts.