Linux 内存状态主要通过 free
命令来查看,包括以下几个关键概念:
基础概念:
优势:
类型:
应用场景:
常见的内存状态指标:
total
:总的物理内存。used
:已使用的内存。free
:空闲的内存。buff/cache
:用于缓存和缓冲区的内存。例如,执行 free -h
命令可能会得到如下输出:
total used free shared buff/cache available
Mem: 7.7G 2.3G 4.8G 268M 647M 4.9G
Swap: 2.0G 0B 2.0G
如果遇到内存不足的问题:
在编程中,如果遇到内存相关的问题,例如内存泄漏:
例如,在 C 语言中,可能导致内存泄漏的代码:
#include <stdio.h>
#include <stdlib.h>
void leakMemory() {
int *ptr = (int *)malloc(sizeof(int));
// 没有释放 ptr 所指向的内存
}
int main() {
for (int i = 0; i < 1000; i++) {
leakMemory();
}
return 0;
}
修改后的代码:
#include <stdio.h>
#include <stdlib.h>
void noLeakMemory() {
int *ptr = (int *)malloc(sizeof(int));
free(ptr);
}
int main() {
for (int i = 0; i < 1000; i++) {
noLeakMemory();
}
return 0;
}
领取专属 10元无门槛券
手把手带您无忧上云