Understanding pointers, structs, and dynamic memory (malloc and free) is the milestone that turns C from a mysterious language into a crystal-clear mental model of how computers store data. In this beginner lesson, you will allocate a dynamic array of student structs at runtime, access fields through pointers, and release memory safely.
Heap memory lifecycle in C
malloc(count * sizeof(Student)) → Check ptr != NULL → Read/Write via ptr[i] or ptr->field → free(ptr); ptr = NULL;
Pointers and the -> Operator
- A pointer stores the memory address of a value rather than copying the whole struct.
- When you have a struct variable
s, use a dot (s.score). When you have a pointerpto a struct, use the arrow operator (p->score). - Every successful
malloc(...)orcalloc(...)call must be paired with exactly onefree(...)call when you finish using the block.
Complete Dynamic Student Array Example
Save this program as students.c and compile with gcc -Wall -Wextra students.c -o students:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
char name[32];
int score;
} Student;
void print_student(const Student *s) {
printf("ID: %d | Name: %s | Score: %d\n", s->id, s->name, s->score);
}
int main(void) {
size_t count = 2;
Student *roster = malloc(count * sizeof(Student));
if (roster == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
return 1;
}
roster[0] = (Student){101, "Aarav", 92};
roster[1] = (Student){102, "Maya", 89};
for (size_t i = 0; i < count; i++) {
print_student(&roster[i]);
}
free(roster);
roster = NULL;
return 0;
}
Three Safety Rules for Beginners
- Always check for
NULL: Never dereference a pointer returned bymallocbefore checkingif (roster == NULL). - Pass structs by
constpointer:print_student(const Student *s)avoids copying the struct and promises the function will not modify it. - Reset freed pointers to
NULL: Settingroster = NULL;afterfree(roster)prevents accidental use-after-free bugs.
Practice
- Add a function
double average_score(const Student *roster, size_t count)that loops through the dynamic array and returns the class average. - Use
reallocto growrosterfrom 2 students to 3 students and add a third student record. - Compile with AddressSanitizer (
gcc -fsanitize=address -g students.c) and intentionally test omittingfree(roster)to watch the leak detector report it.
Continue learning: C Lessons and Practice.
References: cppreference.com C Standard Reference.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.