Communitygithub.com

JantonioFC/skillsbank

C言語向けの慣用的で効率的なコード記法リファレンス。

skillsbank とは?

このスキルはC言語の開発者向けに、メモリ管理、ポインタと配列、エラーハンドリング、文字列操作、構造体と列挙体、プリプロセッサとヘッダ、およびアンチパターンという主要なトピックにわたる慣用的で効率的なコードのガイドラインを提供します。具体的なコード例とともに「悪い例」と「良い例」を示し、なぜその書き方が優れているのかを説明することで、現場で即座に活用できる知識を提供します。Claude Code, Cursor, Codex など様々なAIエージェント開発ツールで利用可能です。本ガイドラインはC言語の機能を最大限に活用し、バグを減らし、保守性を高めるための実践的なルール集であり、各節が明確に分割されているため、必要な部分だけを参照することもできます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/skills/c

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

C: 慣用的効率リファレンス

目次

  1. メモリ管理
  2. ポインタと配列
  3. エラーハンドリング
  4. 文字列
  5. 構造体と列挙体
  6. プリプロセッサとヘッダ
  7. C言語特有のアンチパターン

1. メモリ管理 {#memory}

// ❌ 戻り値をチェックせずにmalloc
char *buf = malloc(size);
strcpy(buf, src);

// ✅
char *buf = malloc(size);
if (!buf) return -ENOMEM;
memcpy(buf, src, size);
// ❌ mallocの結果をキャスト(Cでは不要。 #include 忘れを隠す)
int *p = (int *)malloc(n * sizeof(int));

// ✅
int *p = malloc(n * sizeof *p);
// ❌ freeしてもポインタをNULLにしない(長寿命スコープではダングリングポインタのリスク)
free(ptr);
// ... 後続のコードがptrを使うかもしれない

// ✅
free(ptr);
ptr = NULL;
// ❌ 早期リターンパスでfreeを忘れる
char *a = malloc(100);
char *b = malloc(200);
if (!b) return -1; // aがリーク

// ✅ — 単一のクリーンアップラベル
char *a = NULL, *b = NULL;
a = malloc(100);
if (!a) goto cleanup;
b = malloc(200);
if (!b) goto cleanup;
// ... a, b を使う ...
cleanup:
    free(b);
    free(a);

sizeof(Type) ではなく sizeof *ptr を使用する — 型が変更されても正しく動作します。


2. ポインタと配列 {#pointers}

// ❌ 手動で配列サイズを追跡
void process(int *arr, int len) { ... }
process(data, 10);

// ✅ — サイズをポインタと一緒に渡すか、構造体を使う
typedef struct { int *data; size_t len; } IntSlice;
// ❌ 配列インデックスのほうが明確なのにポインタ演算を使う
*(arr + i) = value;

// ✅
arr[i] = value;
// ❌ プロダクションコードでのVLA(スタックオーバーフローのリスク、C11以降はオプション)
int arr[n];

// ✅
int *arr = malloc(n * sizeof *arr);
if (!arr) return -ENOMEM;
// ... arr を使う ...
free(arr);

3. エラーハンドリング {#errors}

// ❌ エラーリターンにマジックナンバーを使う
if (do_thing() == -1) { ... }

// ✅ — 名前付きエラーコードを定義または使用する
#include <errno.h>
if (do_thing() < 0) {
    perror("do_thing");
    return errno;
}
// ❌ 深くネストしたエラーチェック
int r1 = step1();
if (r1 == 0) {
    int r2 = step2();
    if (r2 == 0) {
        int r3 = step3();
        // ...
    }
}

// ✅ — 早期リターン / gotoクリーンアップ
if (step1() < 0) goto fail;
if (step2() < 0) goto fail;
if (step3() < 0) goto fail;
return 0;
fail:
    cleanup();
    return -1;

goto cleanup はリソース解放のための一般的なC言語のイディオムです — 原則として避けようとしないでください。


4. 文字列 {#strings}

// ❌ 境界チェックなしのstrcpy
strcpy(dest, src);

// ✅
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
// またはより良い方法: snprintf(dest, sizeof(dest), "%s", src);
// ❌ strcmpの誤用
if (str == "hello") { ... } // ポインタを比較、内容ではない

// ✅
if (strcmp(str, "hello") == 0) { ... }
// ❌ 繰り返しstrcatで文字列を構築(O(n²))
char result[1024] = "";
for (int i = 0; i < n; i++) {
    strcat(result, items[i]);
}

// ✅ — 書き込み位置を追跡
char result[1024];
int pos = 0;
for (int i = 0; i < n && pos < (int)sizeof(result); i++) {
    pos += snprintf(result + pos, sizeof(result) - pos, "%s", items[i]);
}

sprintf よりも snprintf を常に優先すること。


5. 構造体と列挙体 {#structs}

// ❌ ベア構造体。どこでも `struct` キーワードが必要
struct point { int x, y; };
struct point p = {1, 2};

// ✅
typedef struct { int x, y; } Point;
Point p = {1, 2};
// ❌ 初期化されていない構造体
Point p;
use(p.x); // 未定義動作

// ✅
Point p = {0};
// ❌ マジック整数定数
if (state == 3) { ... }

// ✅
typedef enum { STATE_IDLE, STATE_RUNNING, STATE_DONE } State;
if (state == STATE_DONE) { ... }

6. プリプロセッサとヘッダ {#preprocessor}

// ❌ インライン関数で代用できるマクロ(型安全性なし、二重評価)
#define MAX(a, b) ((a) > (b) ? (a) : (b))
MAX(x++, y) // x > y の場合、xが2回インクリメントされる

// ✅
static inline int max_int(int a, int b) { return a > b ? a : b; }
// ❌ インクルードガードなし
// my_header.h
struct Foo { int x; };

// ✅
#ifndef MY_HEADER_H
#define MY_HEADER_H
struct Foo { int x; };
#endif
// または: #pragma once(広くサポートされているが標準ではない)

マクロは条件付きコンパイルと定数のために使う。ロジックには static inline を使用する。


7. C言語特有のアンチパターン {#antipatterns}

アンチパターン推奨される方法
sprintfバッファサイズを指定した snprintf
getsfgets(getsはC11で削除)
malloc の結果をキャスト暗黙の void* 変換に任せる
malloc内の sizeof(Type)sizeof *ptr
大規模/ランタイム配列にVLAヒープ割り当て
コンテキストパラメータなしの void* コールバック関数ポインタと一緒に void *ctx を渡す
グローバル可変状態構造体ポインタを介して状態を渡す
ランタイムエラーハンドリングに assert適切なエラーリターンコード
読み取り専用のポインタパラメータに const がないconst char *str
比較で符号あり/なしが混在一貫した型を使用し、明示的にキャスト

制限事項

  • これらは言語固有のガイドラインであり、全体的なアーキテクチャ上の決定を網羅するものではありません。
  • 過度な圧縮は可読性を損なう可能性があるため、判断を適用してください。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

JantonioFC/skillsbank

AI-powered image editing with style transfer and object removal

JantonioFC/skillsbank

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

JantonioFC/skillsbank

Analise e auditoria de editais de leilao judicial e extrajudicial. Riscos ocultos, clausulas perigosas, debitos, ocupante e classificacao da oportunidade.

JantonioFC/skillsbank

Embed Photopea in web apps using photopea.js. Covers embedding, file I/O, scripting, exporting, layers, text, filters, and the full Photoshop-compatible API.

JantonioFC/skillsbank

Best practices for Remotion - Video creation in React

JantonioFC/skillsbank

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

JantonioFC/skillsbank

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

JantonioFC/skillsbank

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

JantonioFC/skillsbank

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

JantonioFC/skillsbank

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

JantonioFC/skillsbank

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

JantonioFC/skillsbank

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

JantonioFC/skillsbank

Tool lifecycle UI components for React/Next.js from ui.inference.sh. Display tool calls: pending, progress, approval required, results. Capabilities: tool status, progress indicators, approval flows, results display. Use for: showing agent tool calls, human-in-the-loop approvals, tool output. Triggers: tool ui, tool calls, tool status, tool approval, tool results, agent tools, mcp tools ui, function calling ui, tool lifecycle, tool pending

JantonioFC/skillsbank

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

JantonioFC/skillsbank

When the user wants help with paid advertising campaigns on Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X, or other ad platforms. Also use when the user mentions 'PPC,' 'paid media,' 'ROAS,' 'CPA,' 'ad campaign,' 'retargeting,' 'audience targeting,' 'Google Ads,' 'Facebook ads,'...

JantonioFC/skillsbank

Create AI avatar and talking head videos with OmniHuman, Fabric, PixVerse via inference.sh CLI. Models: OmniHuman 1.5, OmniHuman 1.0, Fabric 1.0, PixVerse Lipsync. Capabilities: audio-driven avatars, lipsync videos, talking head generation, virtual presenters. Use for: AI presenters, expla...

JantonioFC/skillsbank

Create AI marketing videos for ads, promos, product launches, and brand content. Models: Veo, Seedance, Wan, FLUX for visuals, Kokoro for voiceover. Types: product demos, testimonials, explainers, social ads, brand videos. Use for: Facebook ads, YouTube ads, product launches, brand awarene...

JantonioFC/skillsbank

Generate AI videos with Google Veo, Seedance, Wan, Grok and 40+ models via inference.sh CLI. Models: Veo 3.1, Veo 3, Seedance 1.5 Pro, Wan 2.5, Grok Imagine Video, OmniHuman, Fabric, HunyuanVideo. Capabilities: text-to-video, image-to-video, lipsync, avatar animation, video upscaling, fole...

JantonioFC/skillsbank

Production-ready CI/CD configurations for Playwright — GitHub Actions, GitLab CI, CircleCI, Azure DevOps, Jenkins, Docker, parallel sharding, reporting, code coverage, and global setup/teardown.

JantonioFC/skillsbank

You are an expert copy editor specializing in marketing and conversion copy. Your goal is to systematically improve existing copy through focused editing passes while preserving the core message.

関連スキル