'Sysinfo behaves differently on RPI4(Raspbian) and CM4(Raspbian)

I am using Sysinfo library to calculate ram usage but it gives different results in RPI4 and CM4. It works fine in RPi4 but it returns ridiculous values ​​in CM4. For example,

Sysinfo return totalram 300kB, freeram 308kB, bufferram 9kB.

I looked at the possibility that it might be due to the kernel versions, but there is no difference in the versions.

  • CM4(Raspbian) kernel version 5.10.63-v7l+
  • RPI4(Raspbian) kernel version 5.10.17-v7l+

Code :

        inline static void GetRamCache ()
        {
            char iwbuffer[1024];
            memset(iwbuffer, 0, 1024);
            FILE *iwFile;
            std::string cmd = "cat /proc/meminfo | grep Cached | awk '{print $2}' | head -n 1";
            iwFile = popen(cmd.c_str(), "r");
            fread(iwbuffer, 1, sizeof(iwbuffer) - 1, iwFile);
            fclose(iwFile);

            mCachedRam = std::stoul(std::string(iwbuffer),nullptr,0);
        }

        inline static double GetMemoryUsagePercent (bool ForceGetMemoryCache = true)
        {
            unsigned long mFreeRam = 0;
            unsigned long mBufferRam = 0;
            unsigned long mRamUsed = 0;
            double mPercentageRamUsed = 0;
            struct sysinfo RamInfo;

            if(mCachedRam == 0 || ForceGetMemoryCache)
            {
                GetRamCache();
            }

            try
            {
                if(sysinfo(&RamInfo) != -1)
                {
                    mFreeRam = RamInfo.freeram / 1024; // byte to kB.
                    mBufferRam = RamInfo.bufferram / 1024;

                    if(mTotalRam == 0)
                    {
                        mTotalRam = RamInfo.totalram / 1024;
                    }

                    mRamUsed = (mTotalRam - (mFreeRam + mBufferRam + mCachedRam)) ; //kB
                    mPercentageRamUsed = (((double)mRamUsed / (double)mTotalRam) * 100);
                }
            }
            catch(...)
            {
                std::cout << "GetMemoryUsagePercent EX1" << std::endl;
            }

            return mPercentageRamUsed;
        }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source