UPI Study › Courses › Programming in C › Free lessons › Lesson 11.2 Free with a free account
Allocating Heap Memory: malloc(), calloc(), and realloc()
Programming in C · Chapter 11: Dynamic Memory, Linked Lists, Stacks, and QueuesSection 11.2 · lesson 72 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Releasing Memory and Avoiding Leaks →← Singly Linked List FundamentalsNext lesson: Releasing Memory and Avoiding Leaks →
In this lesson
Requesting, clearing, and growing heap memory at run time.
- Distinguish stack memory for local variables from heap memory for run-time blocks
- Allocate a block with malloc sized as count times sizeof *p and check for NULL
- Use calloc to get a block of counters that all start at zero
- Grow a block safely with realloc through a temporary pointer
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,032 words). Read along, or search it.
Opening Question
How Many Scores Tonight
The tournament at the Starlight Arcade just ended. How many scores did it produce tonight? Ten? Five thousand? When you write the code, you can't know. Every array so far had its size fixed in the source, like int scores of one hundred. Guess too small, and players get turned away. Guess too big, and memory sits empty. C lets a running program ask for exactly the room it needs, at the moment it needs it. That room comes from the heap. This lesson covers malloc, calloc and realloc, and the checks that keep them safe.
Core Idea
Stack Frames Versus the Heap
First, there are two kinds of memory to keep apart. In practice, ordinary local variables live on the stack. A function gets a frame there when it starts, as you saw in 6.1. The sizes on the stack are fixed by your code, and the frame disappears automatically when the function returns. The heap is a big pool for blocks whose size you choose while the program runs. Nothing cleans the heap up for you. A block stays yours until you hand it back. The heap gives you an address, so you keep it in a pointer. The pointer is an ordinary variable on the stack, and the block it points at is on the heap.
Allocation
Asking the Heap for Exactly Enough
Here's Priya's tournament program. It asks how many scores there are, and then makes exactly that much room. malloc, from stdlib dot h, asks the heap for a number of bytes. It returns the address of the first byte. The byte count is how many items, times the size of one item. Write that size as sizeof star scores: the size of whatever scores points to. If the type changes later, this line stays right. Without the star, sizeof scores is the size of the pointer itself, eight bytes here. That block would be far too small. Notice there's no cast. malloc returns a void pointer, a pointer to anything, and C converts it to an int pointer by itself. Old books put a cast in front. C doesn't need it. C++ does, which is why you'll still see it. And the second rule: check for NULL before you use the block. When malloc can't help, it returns NULL.
Sample Run
Averaging Scores in a Heap Block
After that, scores works just like an array. Each score goes into scores of i, and the total adds up. At the end, free gives the block back. Giving memory back is the whole topic of 11.3. Build and run. Sam types four, then four scores: 120, 95, 300 and 85. The average is 150.0. And if Sam typed five thousand, the program would simply ask the heap for five thousand seats.
Quick Check
The Block Outlives the Function
Quick check. make_seats asks malloc for n ints, fills them, and returns the address it got. The pointer s is a local variable. When make_seats returns, which of the two survives: both, the pointer s, neither, or just the block? Pause and predict. Build and run: 10, 20, 30. main can still read all three seats. The block lives on the heap, so the return doesn't touch it. It stays until free hands it back. The pointer s was a local variable on the stack, so it vanished at the return. But its value, the address, was copied into seats first.
Failure Case
When Malloc Says No
Can malloc really say no? This request is one, shifted left sixty times: more than a quintillion bytes. No computer has that much memory. Build and run. malloc said no: block is NULL. The program got a polite NULL, not a crash. Using that NULL as if it were a block would crash the program. The check is the difference between a clear message and a crash.
Zeroed Memory
Calloc Clears Every Byte
A block from malloc holds leftover bytes. Read it before you fill it, and the values mean nothing. calloc does the same job, with two differences. You pass the count and the item size as two separate arguments. And every byte comes back set to zero. That's perfect for counters, like tokens won on each machine. Build and run. All five counters start at zero. Then tokens 2 becomes 40, and nothing else changes.
Growing a Block
Catch Realloc in a Temporary Pointer
Sometimes the room runs out halfway. Say a program starts with two seats for scores, and a third score arrives. realloc asks for a bigger block. The old values come along, and the new seats are unset. The block may move to a new address, so always use the address that realloc returns. Here's the catch. If realloc fails, it returns NULL, and your old block is still valid. Writing scores equals realloc of scores would overwrite your only copy of the address with NULL. The old block would be lost. So catch the answer in a temporary pointer, check it, and only then replace the old one.
Worked Example
Doubling Capacity as Values Arrive
In this program, cap counts the seats, and used counts the filled ones. malloc starts it off with two seats. Each new value checks first: are all the seats used? If so, it asks realloc for twice as many. The answer goes into bigger. Only after the NULL check does scores take the new address. Build and run. It grew to four seats, then to eight, and all six values arrived in order. Doubling keeps the number of realloc calls small: six values needed only two.
Quick Check
Nine Values and Three Growths
Quick check. Change the loop to run up to nine hundred, so nine values arrive. How many times does Grew to print now, and what's the last capacity? Pause and predict. Build and run: three times, ending at sixteen seats, and all nine values are stored. The seats fill at two, four and eight. So the third, the fifth and the ninth value each find no room, and each one doubles the block. Eight seats can't hold nine values, so the last growth is to sixteen, even though only one more seat is needed.
Key Takeaways
Stack, Heap, and Three Allocators
To sum up. Local variables live on the stack. Blocks you ask for live on the heap, and you reach them through a pointer. malloc gives raw bytes. Size it as count times sizeof star p, and check for NULL. calloc gives a block cleared to zero. realloc grows a block. Catch its answer in a temporary pointer first.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Allocating Heap Memory: malloc(), calloc(), and realloc()
What is the difference between the stack and the heap in C?
Do you need to cast the result of malloc in C?
What is the difference between malloc and calloc?
Why is p = realloc(p, size) risky in C?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →