In this article
- How do you create a struct?
- How do you access a struct through a pointer?
- What does malloc do?
- Why is free mandatory?
- Putting it all together: a list node
- What about Go, which has structs and pointers?
- Now you ask: what about Python and PHP?
- How does the same concept show up in each language?
- Now you ask: what does this have to do with performance?
- What are the most common mistakes with malloc and free?
- Now it’s your turn!
A struct is a type created by the programmer that groups several variables, of different types, under a single name. Dynamic memory allocation means asking for a block of memory while the program is running and giving it back when it’s no longer needed. In C, the function that asks is malloc, and the one that gives it back is free.
In the article on tuples, there was a promise: C has no tuples, and what groups values of different types is the struct. And in the article on pointers, you learned to store addresses. Today the two pieces meet. With struct, malloc and free, you start creating new data while the program runs, and that’s exactly what a linked list does with every value it receives. The two ideas don’t belong to a single language: Go also has structs, Python and PHP play the same role with classes, and all four ask for memory and give it back. What changes is who gives it back. This article starts with C, where nothing is hidden, goes through the other three languages and ends with what all this has to do with performance.
Think of the locker room at a gym. You arrive, ask for a locker, and the front desk hands you a key with its number. You use it for as long as you need. On the way out, you give the key back, and the locker is free for someone else. Whoever leaves with the key in their pocket keeps a locker taken for nothing. malloc is the request, the address is the key, and free is the return.

How do you create a struct?
You describe the fields once and then create as many variables of that type as you want. You access each field with a dot:
#include <stdio.h>
struct Student {
char name[20];
int age;
double grade;
};
int main(void)
{
struct Student student = {"Ana", 30, 7.5};
printf("%s\n", student.name);
printf("%d\n", student.age);
student.grade = 8.5;
printf("%.1f\n", student.grade);
return 0;
}
Output:
Ana 30 8.5
Kernighan and Ritchie’s book, The C Programming Language, defines a structure as one or more variables, possibly of different types, grouped under a single name, and notes that some languages call it a record. It’s the same idea as a registration form, with a space for each piece of information.
How do you access a struct through a pointer?
With the arrow. When what you have in hand is the address of the struct, the dot gives way to ->:
#include <stdio.h>
struct Student {
char name[20];
int age;
double grade;
};
int main(void)
{
struct Student student = {"Ana", 30, 7.5};
struct Student *pointer = &student;
(*pointer).grade = 8.0; // the long way
pointer->grade = 9.0; // the short way, with the arrow
printf("%.1f\n", student.grade);
return 0;
}
Output:
9.0
| What you have | How you access the field | Example |
|---|---|---|
| The struct itself | Dot | student.grade |
| The address of the struct | Arrow | pointer->grade |
The two lines of the program do the same thing. The arrow is just a shorthand for (*pointer).grade, and the parentheses in that long form are required, because of the order in which C reads the operators. In practice, the arrow is the form you’ll come across.
What does malloc do?
Until now, every variable had its size decided when the program was written. But the amount of memory is often only known with the program running: how many students will the user register? That’s what dynamic allocation is for.
The malloc function receives the number of bytes you want and returns the address of a block of that size. So that you don’t have to count the bytes by hand, there’s sizeof, which tells you how many bytes a type takes up:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int count = 3;
int *numbers = malloc(count * sizeof(int));
if (numbers == NULL) {
printf("out of memory\n");
return 1;
}
for (int i = 0; i < count; i++) {
numbers[i] = (i + 1) * 10;
}
for (int i = 0; i < count; i++) {
printf("%d\n", numbers[i]);
}
free(numbers);
numbers = NULL;
return 0;
}
Output:
10 20 30

On the machine used to test this example, an int takes up 4 bytes, so the request was for 12 bytes. On another machine the number may be different, and sizeof takes care of that on its own. Also notice that the block is used with square brackets, like any array.
IMPORTANT: memory is finite. When there’s no block available, malloc returns NULL. That’s why the program checks the result before using it, as the GNU C Library manual recommends.
Why is free mandatory?
Because the memory you ask for with malloc isn’t given back on its own when the function ends. It stays reserved until someone calls free.
A program that asks and never gives back takes up more and more memory. This has a name: a memory leak. In a program that runs for two seconds, nobody notices. On a server that stays on for months, it’s a serious problem.
After free, the address stored in the pointer is no longer valid. That’s why the example ends with numbers = NULL: Carnegie Mellon’s SEI CERT C Coding Standard recommends this care, so that the pointer isn’t left dangling, pointing to a block that was already given back.
To check whether your program gave everything back, there’s a tool called Valgrind, which Harvard’s CS50 course uses in its lecture on memory. The programs in this article that use malloc went through it without a single leak.
Putting it all together: a list node
Now the three pieces in the same program. A struct that stores a value and the address of another struct of the same type is called a node. With two linked nodes, you already have a list:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main(void)
{
struct Node *first = malloc(sizeof(struct Node));
struct Node *second = malloc(sizeof(struct Node));
if (first == NULL || second == NULL) {
printf("out of memory\n");
return 1;
}
first->value = 10;
first->next = second;
second->value = 20;
second->next = NULL;
for (struct Node *current = first; current != NULL; current = current->next) {
printf("%d\n", current->value);
}
free(second);
free(first);
return 0;
}
Output:
10 20

Read the for slowly: it starts at the first node, shows the value and jumps to the address stored in next. When it finds NULL, it stops. At the end, one free for each malloc. If you understood this program, the article on the linked list will feel like a natural continuation.
What about Go, which has structs and pointers?
Go has both, and the syntax is similar to C’s. The difference is in memory: you don’t call free. The Go documentation explains that each variable exists as long as there are references to it. When nobody points to the node anymore, the language itself collects the memory.
package main
import "fmt"
type Student struct {
name string
age int
grade float64
}
type Node struct {
value int
next *Node
}
func main() {
student := Student{"Ana", 30, 7.5}
pointer := &student
pointer.grade = 9.0 // the dot also works with the address
fmt.Printf("%s %d %.1f\n", student.name, student.age, student.grade)
second := &Node{value: 20} // the next field starts as nil
first := &Node{value: 10, next: second}
for current := first; current != nil; current = current.next {
fmt.Println(current.value)
}
}
Output:
Ana 30 9.0 10 20
Three details. &Node{...} creates the node and already returns its address, without malloc and without sizeof. The next field that didn’t get a value started as nil, and that’s where the for stopped. And, instead of the arrow, Go used the dot even with the address in hand: pointer.grade and current.next.
Now you ask: what about Python and PHP?
In these languages, the role of the struct is played by the class, and you don’t call malloc or free. Look at it in Python:
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
student = Student("Ana", 30, 7.5)
student.grade = 8.5
print(student.name, student.grade)
Output:
Ana 8.5
And in PHP:
<?php
class Student
{
public function __construct(
public string $name,
public int $age,
public float $grade,
) {
}
}
$student = new Student("Ana", 30, 7.5);
$student->grade = 8.5;
echo $student->name, " ", $student->grade, "\n";
Output:
Ana 8.5
Notice that PHP uses the same arrow as C to get to the field. Memory is still requested and given back, but the language itself does it. The Python documentation explains that the objects live in a memory area managed by the interpreter, and that the programmer has no control over it. Focus on the concept, not the language!
How does the same concept show up in each language?
All four languages have the two ideas of this article: grouping data into a new type and asking for memory with the program running. What changes is the name and, above all, who gives the memory back.
| Language | What groups the data | Who asks for the memory | Who gives it back |
|---|---|---|---|
| C | struct | You, with malloc | You, with free |
| Go | struct | The language, when the value is created | The language, with the garbage collector |
| Python | Class | The language, when the object is created | The language |
| PHP | Class | The language, when the object is created | The language |
In Go, the memory is collected by the garbage collector, the part of the language that finds the memory nobody uses anymore. The PHP manual describes a similar mechanism: each value has a count of how many variables use it, and the memory can be freed when that count reaches zero.
Now you ask: what does this have to do with performance?
A lot! Asking for memory makes the system work, and so does giving it back. The program below measures that work. It stores one million nodes, adds up the values and gives the memory back, in two ways: with one malloc for each node, as in the list from the previous example, and with a single malloc, the size of all the nodes together.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node {
int value;
struct Node *next;
};
int main(void)
{
int count = 1000000;
long long sum = 0;
// first way: one memory request for each node
clock_t start = clock();
struct Node *first = NULL;
for (int i = 0; i < count; i++) {
struct Node *node = malloc(sizeof(struct Node));
if (node == NULL) {
printf("out of memory\n");
return 1;
}
node->value = i;
node->next = first;
first = node;
}
while (first != NULL) {
struct Node *following = first->next;
sum = sum + first->value;
free(first);
first = following;
}
double one_by_one = (double) (clock() - start) * 1000 / CLOCKS_PER_SEC;
// second way: a single request, with room for all the nodes
start = clock();
struct Node *block = malloc(count * sizeof(struct Node));
if (block == NULL) {
printf("out of memory\n");
return 1;
}
for (int i = 0; i < count; i++) {
block[i].value = i;
block[i].next = NULL;
}
for (int i = 0; i < count; i++) {
sum = sum + block[i].value;
}
free(block);
block = NULL;
double all_at_once = (double) (clock() - start) * 1000 / CLOCKS_PER_SEC;
printf("size of a node: %zu bytes\n", sizeof(struct Node));
printf("sum of both ways: %lld\n", sum);
printf("one million requests: %.0f ms\n", one_by_one);
printf("a single request: %.0f ms\n", all_at_once);
return 0;
}
Output (the times change on every run and from one computer to another):
size of a node: 16 bytes sum of both ways: 999999000000 one million requests: 29 ms a single request: 19 ms
Each node takes up 16 bytes on the test machine. With one request for each node, there were one million calls to malloc and one million to free, and the work took 29 milliseconds. With a single request of 16,000,000 bytes, it took 19: the same job in about two thirds of the time. The test was compiled with GCC without optimization options and went through Valgrind without a single leak.
In the languages that give memory back on their own, the work doesn’t disappear: it moves to the language. The Go documentation acknowledges that the garbage collector has a cost and says that avoiding unnecessary garbage can make a huge difference. It also explains that the compiler keeps variables in the function’s own area whenever it can, and only uses the collector’s area when it has to.
That’s why the subject comes back in so many places:
- In data structures: each node of a linked list is a block requested during execution, as in the two-node program.
- In programs that stay on for a long time: memory that is requested and not given back piles up. That’s the memory leak.
- In optimization: fewer memory requests mean less work, for the system or for the collector.
IMPORTANT: the single request only works when the amount is known in advance. The advantage of asking for one node at a time is being able to grow little by little, and that’s what the linked list takes advantage of.
What are the most common mistakes with malloc and free?
- Forgetting free. Each
mallocneeds itsfree, or the memory leaks. - Using the block after free. The address is still in the pointer, but the block isn’t yours anymore.
- Not checking for NULL. If
mallocfails and the program uses the pointer anyway, it crashes. - Asking for the wrong size. Writing the number of bytes by hand is asking for trouble. Use
sizeof. - Calling free twice on the same block. The POSIX manual page for
freesays the behavior is undefined: the block was already given back the first time.
Now it’s your turn!
First on paper. Draw the memory after each line of the two-node program: where each block is and what each pointer stores. Then answer: what would happen if the line second->next = NULL were deleted?
Then, on the computer: create a struct Product with a name and a price, ask for memory for one product with malloc, fill in the fields with the arrow, show them on the screen and release the memory with free. Try it on your own, without asking anyone for the ready-made answer, not even AI!
See you in the next article!
Stay confident!!!
Sources:
- Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, 2nd edition (Prentice Hall, 1988). Chapter 6, Structures, with the structure as one or more variables, possibly of different types, grouped under a single name, which some languages call a record (book).
- Harvard University, CS50. Lecture 4, with
mallocasking for a block of memory,freegiving it back, theNULLreturned when something goes wrong, and Valgrind to find the memory that was never freed. - Harvard University, CS50. Lecture 5, with struct to create new data types, the arrow to reach a field through a pointer, and the list node, which stores a value and the address of the next node, requested with
malloc. - GNU C Library, official manual. Examples of malloc, with the null pointer that
mallocreturns when no more space is available and the advice to check the value of every call. - The Open Group, POSIX manual on man7.org. free(3p), with the undefined behavior when
freereceives space that was already deallocated and when a pointer to freed space is used. - Carnegie Mellon University, SEI CERT C Coding Standard. MEM01-C. Store a new value in pointers immediately after free(), with the dangling pointer and the
NULLthat prevents the same block from being freed twice. - Valgrind, official documentation. The Valgrind Quick Start Guide, with Memcheck, which reports memory errors and leaks, and the
--leak-checkoption. - Go, official documentation. Frequently Asked Questions, with each variable existing as long as there are references to it, the variables the compiler keeps in the function’s stack frame or in the garbage-collected heap, and the effect of avoiding unnecessary garbage.
- Go, official documentation. The Go Programming Language Specification, with the pointer type, the nil value of a pointer that hasn’t been initialized and the address of a composite literal created with &.
- Go, official documentation. A Tour of Go: Pointers to structs, with the field accessed through the pointer as p.X, without the explicit dereference.
- Python, official documentation. Memory Management, with the private heap that holds all Python objects, managed by the interpreter itself, over which the user has no control.
- PHP, official manual. Reference Counting Basics, with the refcount of each value and the variable container that is destroyed when the refcount reaches zero.
- The examples were run on Python 3.13, PHP 8.3, GCC 13 and Go 1.24, and the programs with
mallocwere checked with Valgrind 3.22.

Continue the conversation