c-pro

Write efficient C code with proper memory management, pointer

31,392 stars
Complexity: easy

About this skill

This skill transforms an AI agent into a dedicated C programming expert, focusing on systems programming and performance optimization. It provides comprehensive guidance for writing efficient, secure, and well-managed C code. The agent acts as a C programming specialist, offering detailed expertise in critical areas such as memory management (e.g., `malloc`/`free`, memory pools) and effective pointer handling. It equips the AI to offer actionable steps, validate outcomes, and provide best practices, ensuring high-quality C solutions for complex tasks.

Best use case

Developing new C applications, optimizing existing C code for performance and resource efficiency, implementing robust memory management strategies, understanding and correctly utilizing pointers, or seeking expert guidance on C best practices for systems programming.

Write efficient C code with proper memory management, pointer

Clear, actionable guidance, best practices, and potentially example C code snippets for specific programming challenges. The agent will clarify goals and constraints, apply relevant best practices, validate potential outcomes, and provide concrete steps for implementation and verification, ensuring efficient, safe, and correct C solutions.

Practical example

Example input

I need to implement a dynamic array in C that efficiently handles memory allocation and deallocation. Can you provide a robust code structure and best practices for memory management, including considerations for `realloc` and error handling?

Example output

```
To implement an efficient dynamic array in C with proper memory management, we'll focus on `malloc`, `realloc`, `free`, and robust error handling.

**Goal Clarification:** Create a dynamic array (vector) that can grow or shrink, preventing memory leaks and ensuring data integrity.

**Best Practices & Design:**
1.  **Structure:** Define a struct to hold the array pointer, current size, and allocated capacity.
2.  **Initialization:** A function to initialize the array, allocating an initial capacity.
3.  **Resizing (Growth):** When adding elements beyond capacity, reallocate memory, typically doubling the capacity for amortized O(1) insertions. Always check `realloc` return value.
4.  **Resizing (Shrinkage - Optional):** Consider shrinking when capacity is significantly larger than size to save memory, but be cautious as frequent shrinking can be inefficient.
5.  **Deallocation:** A function to free all allocated memory.
6.  **Error Handling:** Crucial for `malloc`, `realloc`. Return status codes or use assertions.

**Actionable Steps & Code Structure:**

```c
#include <stdio.h>
#include <stdlib.h> // For malloc, realloc, free
#include <string.h> // For memcpy if you store complex structs, or memmove

// Define a simple dynamic array for integers
typedef struct {
    int *data;      // Pointer to the array elements
    size_t size;    // Current number of elements
    size_t capacity; // Allocated memory capacity
} DynamicArray;

// Initialize the dynamic array
int init_array(DynamicArray *arr, size_t initial_capacity) {
    if (!arr) return -1; // Invalid array pointer
    arr->data = (int *)malloc(initial_capacity * sizeof(int));
    if (!arr->data) {
        fprintf(stderr, "Error: Initial memory allocation failed.\n");
        arr->size = 0;
        arr->capacity = 0;
        return -1; // Allocation failed
    }
    arr->size = 0;
    arr->capacity = initial_capacity;
    return 0; // Success
}

// Add an element to the dynamic array
int add_element(DynamicArray *arr, int value) {
    if (!arr) return -1;

    // Check if resize is needed
    if (arr->size == arr->capacity) {
        size_t new_capacity = arr->capacity == 0 ? 1 : arr->capacity * 2; // Start with 1 if 0, then double
        if (new_capacity == 0) new_capacity = 1; // Prevent overflow if capacity was very large

        int *new_data = (int *)realloc(arr->data, new_capacity * sizeof(int));
        if (!new_data) {
            fprintf(stderr, "Error: Memory reallocation failed when adding element.\n");
            return -1; // Reallocation failed
        }
        arr->data = new_data;
        arr->capacity = new_capacity;
    }

    arr->data[arr->size++] = value;
    return 0; // Success
}

// Free the dynamic array's memory
void free_array(DynamicArray *arr) {
    if (arr && arr->data) {
        free(arr->data);
        arr->data = NULL; // Prevent double-free
        arr->size = 0;
        arr->capacity = 0;
    }
}

// Example Usage:
int main() {
    DynamicArray my_array;
    if (init_array(&my_array, 4) != 0) {
        return 1; // Handle initialization error
    }

    for (int i = 0; i < 10; ++i) {
        if (add_element(&my_array, i * 10) != 0) {
            fprintf(stderr, "Failed to add element %d\n", i * 10);
            break;
        }
        printf("Added %d. Current size: %zu, Capacity: %zu\n", i*10, my_array.size, my_array.capacity);
    }

    printf("\nElements in array: ");
    for (size_t i = 0; i < my_array.size; ++i) {
        printf("%d ", my_array.data[i]);
    }
    printf("\n");

    free_array(&my_array);
    return 0;
}
```

**Verification:**
*   Compile and run the `main` function to observe memory growth and element addition.
*   Use memory profiling tools (like Valgrind) to confirm no memory leaks or invalid memory access.
*   Test edge cases: adding to an empty array, adding many elements, freeing an already freed array (should be robust if `data` is NULL after free).

When to use this skill

  • When working on C programming tasks or workflows, especially those requiring high efficiency and careful resource management. When needing expert guidance, best practices, or checklists for C development, particularly concerning memory management, pointer safety, and performance optimization.

When not to use this skill

  • When the task is unrelated to C programming. When you need assistance in a different programming language or domain. When the task requires a tool or domain expertise outside the scope of C code generation and guidance.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/c-pro/SKILL.md --create-dirs "https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/plugins/antigravity-awesome-skills-claude/skills/c-pro/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/c-pro/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How c-pro Compares

Feature / Agentc-proStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

Write efficient C code with proper memory management, pointer

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

## Use this skill when

- Working on c pro tasks or workflows
- Needing guidance, best practices, or checklists for c pro

## Do not use this skill when

- The task is unrelated to c pro
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are a C programming expert specializing in systems programming and performance.

## Focus Areas

- Memory management (malloc/free, memory pools)
- Pointer arithmetic and data structures
- System calls and POSIX compliance
- Embedded systems and resource constraints
- Multi-threading with pthreads
- Debugging with valgrind and gdb

## Approach

1. No memory leaks - every malloc needs free
2. Check all return values, especially malloc
3. Use static analysis tools (clang-tidy)
4. Minimize stack usage in embedded contexts
5. Profile before optimizing

## Output

- C code with clear memory ownership
- Makefile with proper flags (-Wall -Wextra)
- Header files with proper include guards
- Unit tests using CUnit or similar
- Valgrind clean output demonstration
- Performance benchmarks if applicable

Follow C99/C11 standards. Include error handling for all system calls.

Related Skills

n8n-code-javascript

31392
from sickn33/antigravity-awesome-skills

Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using $input/$json/$node syntax, making HTTP requests with $helpers, working with dates using DateTime, troubleshooting Code node errors, or choosing between Code node modes.

Programming & DevelopmentClaude

javascript-pro

31392
from sickn33/antigravity-awesome-skills

Master modern JavaScript with ES6+, async patterns, and Node.js APIs. Handles promises, event loops, and browser/Node compatibility.

Programming & DevelopmentClaude

java-pro

31392
from sickn33/antigravity-awesome-skills

Master Java 21+ with modern features like virtual threads, pattern matching, and Spring Boot 3.x. Expert in the latest Java ecosystem including GraalVM, Project Loom, and cloud-native patterns.

Programming & DevelopmentClaude

haskell-pro

31392
from sickn33/antigravity-awesome-skills

Expert Haskell engineer specializing in advanced type systems, pure

Programming & DevelopmentClaude

cpp-pro

31392
from sickn33/antigravity-awesome-skills

Write idiomatic C++ code with modern features, RAII, smart pointers, and STL algorithms. Handles templates, move semantics, and performance optimization.

Programming & DevelopmentClaude

nft-standards

31392
from sickn33/antigravity-awesome-skills

Master ERC-721 and ERC-1155 NFT standards, metadata best practices, and advanced NFT features.

Web3 & BlockchainClaude

nextjs-app-router-patterns

31392
from sickn33/antigravity-awesome-skills

Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

Web FrameworksClaude

new-rails-project

31392
from sickn33/antigravity-awesome-skills

Create a new Rails project

Code GenerationClaude

networkx

31392
from sickn33/antigravity-awesome-skills

NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs.

Network AnalysisClaude

network-engineer

31392
from sickn33/antigravity-awesome-skills

Expert network engineer specializing in modern cloud networking, security architectures, and performance optimization.

Network EngineeringClaude

nestjs-expert

31392
from sickn33/antigravity-awesome-skills

You are an expert in Nest.js with deep knowledge of enterprise-grade Node.js application architecture, dependency injection patterns, decorators, middleware, guards, interceptors, pipes, testing strategies, database integration, and authentication systems.

Frameworks & LibrariesClaude

nerdzao-elite

31392
from sickn33/antigravity-awesome-skills

Senior Elite Software Engineer (15+) and Senior Product Designer. Full workflow with planning, architecture, TDD, clean code, and pixel-perfect UX validation.

Software DevelopmentClaude