mcpField
C
c-lang

c-lang

github.com/htlin222开发7846 次安装3 周前更新
代码仓库

关于 c-lang

面向系统编程、嵌入式开发和性能关键代码的 C 开发技能,涵盖内存管理、错误处理、调试及实用编码规范。

主要功能

  1. 01内存分配与清理模式
  2. 02系统调用错误检查
  3. 03数据结构示例
  4. 04编译器警告标志
  5. 05使用 Valgrind 和 GDB 调试

适用场景

  1. 01排查内存泄漏
  2. 02编写嵌入式 C 代码
  3. 03处理文件和系统调用
  4. 04分析并优化 C 代码

安装

复制下面的命令,在终端中运行。

$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 进行性能分析,找出热点并优化关键路径

评论

支持 Markdown