Advanced · C PROGRAMMING

Dynamic memory allocation

What you will learn

Request memory and release it after use.

Understand the concept

calloc allocates storage for a requested number of elements and initializes the bytes to zero. Always check for allocation failure before accessing the result. free releases allocated storage. This example uses a small fixed count; for external sizes also check arithmetic bounds.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

Values: 12 0

Practise

Store three values, print their sum and keep exactly one free call for the allocation.

Common mistake

Do not use freed memory or free the same allocation twice. Returning early after allocation can leak memory unless you release it first.

Lesson discussion

Log in to participate.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t count = 3;
    int *values = calloc(count, sizeof *values);
    if (values == NULL) return 1;
    values[0] = 12;
    printf("Values: %d %d\n", values[0], values[1]);
    free(values);
    values = NULL;
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
Values: 12 0
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA