linux下C程序查看内存剩余大小

嵌入式linux中很多内存资源都比较小,所以很多程序中在malloc时就需要提前知道内存剩余的大小

下面是一种调用 sysinfo接口来实现。

示例代码如下:

cpp 复制代码
#include <stdio.h>
#include <linux/kernel.h>
#include <linux/unistd.h>
#include <sys/sysinfo.h>
 
int main(void)
{
    struct sysinfo s_info;
    int error = sysinfo(&s_info);
    printf("error0: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
    //func_call1(pcModelName);
 
    error = sysinfo(&s_info);
    printf("error1: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
 
    int msg[500];
    int i = 0;
    for(i = 0; i < 1; i++)
    {
        //func_call2(pcSrcFile, msg);
        error = sysinfo(&s_info);
        printf("error2: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
 
        //func_call3(pcSrcFile, msg);
        error = sysinfo(&s_info);
        printf("error3: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
    }
 
    //func_call4();
    error = sysinfo(&s_info);
    printf("error4: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
}
相关推荐
高山有多高2 小时前
【Linux笔记】线程概念与控制
linux
阳光九叶草LXGZXJ2 小时前
达梦数据库-学习-69-DM9主备集群部署
linux·运维·服务器·数据库·sql·学习
Sun 32852 小时前
Linux 常用命令梳理
linux·运维·服务器·开发·常用命令
Chen—LSN3 小时前
数据结构——拿捏复杂度
java·c语言·开发语言·数据结构·经验分享·笔记·算法
一条破秋裤3 小时前
Linux 线程同步:条件变量
java·linux·jvm
Chen_harmony3 小时前
六、排序详解
c语言·数据结构·算法·排序算法
LRL_3 小时前
【K8s 存储】Longhorn v1.12.1 离线安装全流程:外网制作离线包 + 内网部署(附踩坑实录)
linux·windows·node.js
星恒随风3 小时前
Linux开发工具详解(一):软件包管理、Vim、GCC/G++、Makefile与进度条实战
linux·运维·笔记·学习·vim
小小、码农3 小时前
Ubuntu / Linux 软件安装完整笔记
linux·笔记·ubuntu
yunwei373 小时前
eBPF 开发实践:使用 sockops 加速网络请求转发
linux·后端·性能优化