Allocating Heap Memory: malloc(), calloc(), and realloc()

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

← Singly Linked List FundamentalsNext lesson: Releasing Memory and Avoiding Leaks →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Local variables normally live on the stack, in a frame that appears when a function starts and disappears automatically when it returns, with sizes fixed by the code. The heap is a pool for blocks whose size is chosen while the program runs. A heap block stays allocated until free returns it, so it can outlive the function that requested it, as long as its address is kept.
Do you need to cast the result of malloc in C?
No. malloc returns a void pointer, and C converts it to any object pointer type automatically, so int *scores = malloc(n * sizeof *scores); needs no cast. Older books often add one, and C++ requires it, which is why casts still appear in examples. Writing sizeof *scores instead of a type name keeps the size correct if the pointer's type changes later.
What is the difference between malloc and calloc?
malloc takes one byte count and returns a block whose contents are leftover values, while calloc takes the item count and the item size as two arguments and sets every byte to zero. calloc(5, sizeof(int)) gives five int counters that all start at 0, ready to be increased. Both return NULL when the request cannot be met, so check either result before using it.
Why is p = realloc(p, size) risky in C?
If realloc fails, it returns NULL but leaves the original block valid, so assigning straight back to p overwrites the only copy of the block's address and leaks it. Store the result in a temporary pointer, check it for NULL, and only then assign it to p. On success, always use the returned address, because the block may have moved.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →