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

嵌入式linux中很多内存资源都比较小,所以很多程序中在malloc时就需要提前知道内存剩余的大小
下面是一种调用 sysinfo接口来实现。

示例代码如下:

#include 
#include 
#include 
#include 
 
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);
}

你可能感兴趣的:(Linux,C应用程序,linux,c语言)