C Workshop · Allocate an int
Lesson C

Allocate an int

malloc one int, set it to 7, print it, then free.

What it is

You rent one int from the heap, write 7 into it, print 7, then check out with free. stdlib.h is the desk that hands out malloc and free.

Approach

  1. p = malloc(sizeof(int));
  2. if (!p) return 1;
  3. *p = 7; printf; free(p);

Where this is used in the real world

Diagram

1

malloc

1 int

2

*p=7

store

3

print

7

4

free

done

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2#include <stdlib.h>
3int main(void) {
4    int *p = malloc(sizeof(int));
5    if (!p) return 1;
6    *p = 7;
7    printf("%d\n", *p);
8    free(p);
9    return 0;
10}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. Prints:

*p = 7.

2. stdlib.h is needed for:

Heap API.

3. sizeof(int) is used so that:

Portable byte count.

4. free twice is:

Once.

5. realloc would be the kind you use to:

Resize.