在 CentOS 上用 Fortran 写程序时,“内存怎么管”通常可以从 语言层面 和 系统/运行环境层面 两个角度来看。下面给你一个比较实用的总结。
real :: a(1000)
⚠️ 大数组不要写在子程序里当局部静态数组,容易段错误。
subroutine foo(n)
integer :: n
real :: b(n)
查看/修改栈大小:
ulimit -s
ulimit -s unlimited
使用 allocatable:
real, allocatable :: c(:)
allocate(c(1000000))
c = 0.0
deallocate(c)
✅ 优点:
⚠️ 注意:
deallocatestat= 检查是否分配成功allocate(c(n), stat=ierr)
if (ierr /= 0) stop "memory alloc failed"
real, allocatable :: d(:)
d = [1.0, 2.0, 3.0]
free -h
top
htop
ulimit -s unlimited
写进 ~/.bashrc:
ulimit -s unlimited
gfortran -O2 -fcheck=all -Wall program.f90
常用:
-fcheck=all:检测数组越界、内存错误-g:调试信息-O2:优化valgrind --tool=memcheck ./a.out
适合:
allocate 没 deallocate| 问题 | 原因 | 解决 |
|---|---|---|
| 段错误 | 栈数组太大 | 用 allocatable |
| 内存泄漏 | 忘记 deallocate | valgrind |
| 越界 | 数组下标错 | -fcheck=all |
| 莫名其妙崩溃 | 混用 C/Fortran 内存 | 明确 owner |
✅ 大数组一律 allocatable
✅ 子程序里不要静态大数组
✅ 编译加 -fcheck=all
✅ 上线前用 valgrind 查一遍
✅ ulimit -s unlimited
如果你愿意,可以告诉我:
我可以直接给你一套 适合你场景的内存管理模板。