Dynamic memory
malloc reserves memory; free returns it. Every path must agree.
What you will be able to do
- Check malloc for NULL before using the result.
- Free exactly once; set the pointer to NULL after freeing when it may be reused.
- Compile with -fsanitize=address during development.
In plain English
Dynamic memory is needed when the size is unknown at compile time. Check every allocation, avoid use-after-free, and make ownership explicit. AddressSanitizer turns many invisible memory bugs into actionable reports.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t length = 3;
int *scores = malloc(length * sizeof(int));
if (scores == NULL) {
return 1;
}
scores[0] = 8;
scores[1] = 9;
scores[2] = 7;
printf("%d\n", scores[1]);
free(scores);
scores = NULL;
return 0;
}Your turn
MediumAllocate and free a score array
Allocate an array of five ints, check the allocation, write one value and free it.
C · starter
int *scores = NULL;Check your understanding before moving on.
Knowledge checkQuestion 1
What is use-after-free?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.