Grace's Dev Site
write关于我
闭坑指南 · C#内存 #经典错误

缓冲区溢出

写入超过分配大小的数据,破坏栈/堆上相邻内存。

缓冲区溢出

典型场景

char buf[8];
strcpy(buf, "very long string");  // 灾难

strcpy / gets / 无边界 scanf("%s") 是历史漏洞温床。

防护

  • snprintf(buf, sizeof(buf), ...)
  • fgets 代替 gets
  • 编译器选项 -fstack-protector、AddressSanitizer 做检测
  • 能换更安全 API 就换(C11 bounds-checking 可选)

与 Python 的关系

Python 列表会自动扩容,但 ctypes / C 扩展 仍可能把 C 的溢出带进进程。

在线运行 C

GCC (Piston)