name: C语言 description: 编写高效的C代码,正确管理内存和系统调用。用于C优化、内存问题或系统编程。
C 开发
为系统编程编写安全、高效的C代码。
何时使用
- 编写C代码
- 内存管理问题
- 系统编程
- 嵌入式系统
- 性能关键代码
内存管理
分配模式
// 始终检查malloc
void* ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "malloc 失败
");
return -1;
}
// 配对malloc与free
char* buffer = malloc(1024);
// ... 使用 buffer ...
free(buffer);
buffer = NULL; // 防止使用后释放
// 使用calloc进行零初始化内存
int* array = calloc(count, sizeof(int));
// 安全地realloc
void* new_ptr = realloc(ptr, new_size);
if (new_ptr == NULL) {
free(ptr); // 失败时原指针仍有效
return -1;
}
ptr = new_ptr;
常见模式
// 使用goto实现RAII风格清理
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;
// ... 处理 ...
result = 0;
cleanup:
free(buffer);
if (fp) fclose(fp);
return result;
}
数据结构
// 链表节点
typedef struct Node {
void* data;
struct Node* next;
} Node;
// 动态数组
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;
}
错误处理
// 检查所有系统调用
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;
}
调试
# 编译时包含调试符号
gcc -g -Wall -Wextra -Werror -o prog prog.c
# 使用valgrind运行
valgrind --leak-check=full ./prog
# GDB调试
gdb ./prog
(gdb) break main
(gdb) run
(gdb) print variable
(gdb) backtrace
最佳实践
- 检查所有返回值
- 初始化所有变量
- 尽可能使用
const - 当大小已知时,优先使用栈而非堆
- 使用
-Wall -Wextra -Werror标志
示例
输入: “修复内存泄漏” 操作: 运行valgrind,跟踪分配,确保每个malloc都有free
输入: “优化此C代码” 操作: 使用perf进行分析,识别热点,优化关键路径