๐ค
C
Avoid common C mistakes โ memory leaks, buffer overflows, undefined behavior, and pointer traps.
ๅฎๅ
จ้่ฟ
ๆ่ฝ่ฏดๆ
name: C slug: c version: 1.0.1 description: Write safe C avoiding memory corruption, buffer overflows, and undefined behavior traps. metadata: {"clawdbot":{"emoji":"โ๏ธ","requires":{"bins":["gcc","clang"]},"os":["linux","darwin","win32"]}}
Quick Reference
| Topic | File |
|---|---|
| malloc/free, leaks, double free | memory.md |
| Null, dangling, pointer arithmetic | pointers.md |
| Null terminator, buffer overflow | strings.md |
| Integer overflow, signed/unsigned | types.md |
| Macro traps, include guards | preprocessor.md |
| Common undefined behavior | undefined.md |
Critical Rules
mallocreturnsvoid*โ cast required in C++, optional in C but check for NULLfree(ptr); ptr = NULL;โ always null after free to prevent double-freesizeof(array)in function gives pointer size, not array size โ pass length separatelychar str[5] = "hello";โ no room for null terminator, UB when used as stringstrcpydoesn't check bounds โ usestrncpyand manually null-terminate- Signed overflow is UB โ compiler can optimize assuming it never happens
i++ + i++is UB โ no sequence point between modifications- Returning pointer to local variable โ dangling pointer, UB on use
#define SQUARE(x) x*xโSQUARE(1+2)=1+2*1+2= 5, not 9memcpywith overlapping regions โ usememmoveinstead- Uninitialized variables โ contain garbage, UB if used
- Array out of bounds โ no runtime check, silent corruption or crash
ๅฆไฝไฝฟ็จใCใ๏ผ
- ๆๅผๅฐ้พ่พAI๏ผWeb ๆ iOS App๏ผ
- ็นๅปไธๆนใ็ซๅณไฝฟ็จใๆ้ฎ๏ผๆๅจๅฏน่ฏๆกไธญ่พๅ ฅไปปๅกๆ่ฟฐ
- ๅฐ้พ่พAI ไผ่ชๅจๅน้ ๅนถ่ฐ็จใCใๆ่ฝๅฎๆไปปๅก
- ็ปๆๅณๆถๅ็ฐ๏ผๆฏๆ็ปง็ปญๅฏน่ฏไผๅ