Allocating a new node in memory
What you'll learn: How to use dynamic memory allocation to create a single link in your data chain.
The blueprint vs. the building
In previous lessons, you defined a struct for a node. Think of that struct as a blueprint for a LEGO brick. Defining the struct doesn't actually give you a brick; it just tells C what one should look like. To actually build a list, you need to grab physical space in your computer's RAM for each individual brick as you go.
Unlike an array, where you decide the size upfront (like buying a fixed-size egg carton), a linked list grows one node at a time. We do this using malloc (memory allocation).
Using malloc for a node
To allocate a node, you need a pointer to act as a handle. You then ask malloc to set aside exactly enough bytes to hold your struct.
Here is the standard way to bring a new node into existence:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
// 1. Create a pointer to hold the address of our new node
struct Node* newNode = NULL;
// 2. Request memory from the heap
// sizeof(struct Node) ensures we get the exact right amount of bytes
newNode = (struct Node*)malloc(sizeof(struct Node));
// 3. Always check if the allocation worked
if (newNode == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// 4. Initialize the node's members
newNode->data = 42;
newNode->next = NULL; // It's not pointing to anyone else yet!
printf("Node created with value: %d\n", newNode->data);
// Clean up when finished
free(newNode);
return 0;
}
Why this matters
When you call malloc, the computer finds a vacant spot in the "Heap"—a large pool of available memory. It hands you the starting address of that spot.
By setting newNode->next = NULL, you are essentially saying, "This is a valid node, but it isn't connected to a chain yet." Without this step, the next pointer would contain "garbage" data—a random memory address that could cause your program to crash if you tried to follow it.
Every time you want to add an item to your linked list, you will repeat this process: allocate, verify, and initialize.
Key takeaway
Use malloc with sizeof(struct Node) to carve out space in memory for each new link in your list.