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);
}
相关推荐
我叫安查查7 分钟前
在Ubuntu系统上使用docker部署GPUStack教程【亲测成功】
linux·ubuntu·docker·gpustack
良木生香8 分钟前
【数据结构-初阶】详解线性表(2)---单链表
c语言·数据结构·算法
脑壳疼___15 分钟前
ubuntu安装postgresql、postgis、pgrouting
linux·ubuntu·postgresql
达子66619 分钟前
git-lfs的安装配置,解决大文件存储问题
linux·c++·git
chenyuhao202421 分钟前
Linux系统编程:基础IO
linux·运维·服务器
超风23 分钟前
Ubuntu可以输入中文,但是IDEA没法输入中文
linux·运维·ubuntu
dangdang___go27 分钟前
使用国产AI模型进行“委婉劝学程序”的模拟实现||创建可执行程序营造惊喜感
c语言·c++·豆包·劝学程序开发·创建可执行文件营造惊喜感
默|笙33 分钟前
【Linux】进程(3)状态
linux·运维·服务器
vortex536 分钟前
浅谈Linux文件读取类漏洞的额外攻击面
linux·安全·web安全
_OP_CHEN37 分钟前
【Git原理与使用】(三)Git 分支管理终极指南:从基础操作到企业级实战,解锁高效协作密码
linux·运维·git·git分支管理·企业级组件·企业协作