Use when managing memory in C programs with malloc/free, pointers, and avoiding common memory safety pitfalls.
View on GitHubSelect agents to install to:
npx add-skill https://github.com/TheBushidoCollective/han/blob/main/jutsu/jutsu-c/skills/c-memory-management/SKILL.md -a claude-code --skill c-memory-managementInstallation paths:
.claude/skills/c-memory-management/# C Memory Management
Master manual memory management in C with proper allocation, deallocation,
pointer handling, and techniques to avoid memory leaks and corruption.
## Overview
C requires manual memory management through explicit allocation and
deallocation. Understanding pointers, the heap, and proper memory handling is
crucial for writing safe and efficient C programs.
## Installation and Setup
### Compiler and Tools
```bash
# Install GCC compiler
# macOS
xcode-select --install
# Linux (Ubuntu/Debian)
sudo apt-get install build-essential
# Check installation
gcc --version
# Memory debugging tools
# Install Valgrind (Linux)
sudo apt-get install valgrind
# Install Address Sanitizer (built into GCC/Clang)
gcc -fsanitize=address -g program.c -o program
```
### Compilation Flags
```bash
# Basic compilation
gcc program.c -o program
# With warnings and debugging
gcc -Wall -Wextra -g program.c -o program
# With Address Sanitizer
gcc -fsanitize=address -g program.c -o program
# With optimization
gcc -O2 -Wall program.c -o program
```
## Core Patterns
### 1. Dynamic Memory Allocation
```c
// malloc - allocate memory
#include <stdlib.h>
#include <string.h>
int* allocate_array(size_t size) {
int* arr = malloc(size * sizeof(int));
if (arr == NULL) {
return NULL; // Allocation failed
}
return arr;
}
// calloc - allocate and zero-initialize
int* allocate_zeroed_array(size_t size) {
int* arr = calloc(size, sizeof(int));
if (arr == NULL) {
return NULL;
}
return arr;
}
// realloc - resize allocation
int* resize_array(int* arr, size_t old_size, size_t new_size) {
int* new_arr = realloc(arr, new_size * sizeof(int));
if (new_arr == NULL && new_size > 0) {
// Reallocation failed, original array still valid
return NULL;
}
return new_arr;
}
// free - deallocate memory
void cleanup_array(int** arr) {
if (arr != NULL && *arr != NULL) {
free(*arr);
*arr = NULL; // P