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);
}
相关推荐
坚持编程的菜鸟1 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵
武文斌771 小时前
复习总结最终版:单片机
linux·单片机·嵌入式硬件·学习
驱动探索者1 小时前
贝尔实验室发展史:20世纪科技圣殿的辉煌与沉浮
linux
何朴尧1 小时前
centos/cuos如何开启软件源
linux·运维·centos
YouEmbedded2 小时前
解码Linux文件IO之标准IO
linux·文件io·系统io
机器视觉知识推荐、就业指导2 小时前
C语言中的预编译是什么?何时需要预编译?
c语言·开发语言
撬动未来的支点2 小时前
【Linux内核】Linux内核裁剪完全指南:从理论到实战的系统优化
linux
csdn_Hzx3 小时前
Linux添加一个系统服务
linux·运维·服务器
洛克大航海3 小时前
Ubuntu安装Hbase
大数据·linux·数据库·ubuntu·hbase
赖small强3 小时前
Linux内存管理-缓存系统中的Major和Minor详解
linux·缓存·交换缓存机制·major fault·minor fault