Communitygithub.com

JantonioFC/skillsbank

C语言习语式高效编码参考,提供语言特定的代码规范指南。

skillsbank 是什么?

该技能为使用C语言的开发者提供了一套全面且具体的代码规范指南,覆盖内存管理、指针与数组、错误处理、字符串、结构体与枚举、预处理器与头文件以及C语言特有反模式等关键领域。它通过大量正反对比例子(如使用✅和❌标记)清晰展示了最佳实践和常见陷阱,帮助开发者编写更安全、高效、可维护的C代码。该技能适用于任何支持技能导入的AI编码助手(如Claude Code、Cursor等),用户通过导入`JantonioFC/skillsbank`技能,即可在对话中让AI助手遵循这套C语言编码规范。指南基于C11标准,特别强调了内存安全、错误处理、资源管理以及避免未定义行为的重要性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/skills/c

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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后未置空指针(长生命周期作用域中悬挂指针风险)
free(ptr);
// ... 后续代码可能使用 ptr

// ✅
free(ptr);
ptr = NULL;
// ❌ 在提前返回路径上忘记释放
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 *ptr 而不是 sizeof(Type) —— 当类型改变时它仍然正确。


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]);
}

优先使用 snprintf 而不是 sprintf —— 始终如此。


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 会自增两次

// ✅
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 处理运行时错误使用恰当的错误返回码
只读指针参数缺少 constconst 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.

相关技能