mcpField
C
c-lang

c-lang

github.com/htlin222開発7846 回インストール4 週間前に更新
リポジトリ

c-lang について

システムプログラミング、組み込み開発、性能が重要なコードに取り組む人向けの C 開発スキルです。メモリ管理、エラー処理、デバッグ、実践的なコーディング規約を扱います。

主な機能

  1. 01メモリ割り当てと解放のパターン
  2. 02システムコールのエラーチェック
  3. 03データ構造の例
  4. 04コンパイラ警告フラグ
  5. 05Valgrind と GDB によるデバッグ

活用シーン

  1. 01メモリリークの調査
  2. 02組み込み C コードの作成
  3. 03ファイルとシステムコールの処理
  4. 04C コードのプロファイリングと最適化

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/htlin222/dotfiles --skill c-lang

インストール後、Claude Code で/c-langを入力して読み込まれたか確認します。

詳細

C 開発

システムプログラミング向けに、安全で効率的な C コードを記述します。

使用する場面

  • C コードの記述
  • メモリ管理の問題
  • システムプログラミング
  • 組み込みシステム
  • パフォーマンスが重視されるコード

メモリ管理

割り当てパターン
// Always check malloc
void* ptr = malloc(size);
if (ptr == NULL) {
    fprintf(stderr, "malloc failed\n");
    return -1;
}

// Pair malloc with free
char* buffer = malloc(1024);
// ... use buffer ...
free(buffer);
buffer = NULL;  // Prevent use-after-free

// Use calloc for zero-initialized memory
int* array = calloc(count, sizeof(int));

// Realloc safely
void* new_ptr = realloc(ptr, new_size);
if (new_ptr == NULL) {
    free(ptr);  // Original still valid on failure
    return -1;
}
ptr = new_ptr;
一般的なパターン
// RAII-style cleanup with goto
int process_file(const char* path) {
    int result = -1;
    FILE* fp = NULL;
    char* buffer = NULL;

    fp = fopen(path, "r");
    if (!fp) goto cleanup;

    buffer = malloc(1024);
    if (!buffer) goto cleanup;

    // ... process ...
    result = 0;

cleanup:
    free(buffer);
    if (fp) fclose(fp);
    return result;
}

データ構造

// Linked list node
typedef struct Node {
    void* data;
    struct Node* next;
} Node;

// Dynamic array
typedef struct {
    void** items;
    size_t count;
    size_t capacity;
} DynArray;

int dynarray_push(DynArray* arr, void* item) {
    if (arr->count >= arr->capacity) {
        size_t new_cap = arr->capacity ? arr->capacity * 2 : 8;
        void** new_items = realloc(arr->items, new_cap * sizeof(void*));
        if (!new_items) return -1;
        arr->items = new_items;
        arr->capacity = new_cap;
    }
    arr->items[arr->count++] = item;
    return 0;
}

エラー処理

// Check all system calls
int fd = open(path, O_RDONLY);
if (fd == -1) {
    perror("open");
    return -1;
}

ssize_t n = read(fd, buf, sizeof(buf));
if (n == -1) {
    perror("read");
    close(fd);
    return -1;
}

デバッグ

# Compile with debug symbols
gcc -g -Wall -Wextra -Werror -o prog prog.c

# Run with valgrind
valgrind --leak-check=full ./prog

# GDB debugging
gdb ./prog
(gdb) break main
(gdb) run
(gdb) print variable
(gdb) backtrace

ベストプラクティス

  • すべての戻り値を確認します
  • すべての変数を初期化します
  • 可能な場合は const を使用します
  • サイズがわかっている場合は、ヒープよりスタックを優先します
  • -Wall -Wextra -Werror フラグを使用します

例

入力: 「メモリリークを修正」 アクション: valgrind を実行して割り当てを追跡し、すべての malloc に対応する free があることを確認します

入力: 「この C コードを最適化」 アクション: perf でプロファイリングしてホットスポットを特定し、クリティカルパスを最適化します

コメント