Search code examples
clinuxshared-libraries

Why is a linux shared library .so possibly larger in memory than on disk?


I'm starting to code more in linux and trying to get a better feel for the environment/APIs which are very different from windows. Anyhow, I'm dabbling with shared libraries .so (versus a windows .dll) and noticed that when a shared object is loaded into memory, it's surprisingly LARGER by 7752 bytes than it was on disk? I was expecting the image on disk to match the image in memory, or maybe there's a bug in my demo code below?

Example from godbolt shows this output:

Program returned: 0
Program stdout
Loaded: linux-vdso.so.1
Loaded: /lib/x86_64-linux-gnu/libc.so.6
---------------------MEMORY-------------------------
libc.so.6 size: 2037344 bytes
7fb5733e4000  7f 45 4c 46 02 01 01 03 00 00 00 00 00 00 00 00   .ELF............
7fb5733e4010  03 00 3e 00 01 00 00 00 c0 41 02 00 00 00 00 00   ..>......A......
7fb5733e4020  40 00 00 00 00 00 00 00 18 e7 1e 00 00 00 00 00   @...............
...
7fb5735d5630  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
7fb5735d5640  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
7fb5735d5650  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................
---------------------DISK-------------------------
libc.so.6 size: 2029592 bytes
7fb5731f2010  7f 45 4c 46 02 01 01 03 00 00 00 00 00 00 00 00   .ELF............
7fb5731f2020  03 00 3e 00 01 00 00 00 c0 41 02 00 00 00 00 00   ..>......A......
7fb5731f2030  40 00 00 00 00 00 00 00 18 e7 1e 00 00 00 00 00   @...............
...
7fb5733e17f8  00 00 00 00 00 00 00 00 c8 e2 1e 00 00 00 00 00   ................
7fb5733e1808  4b 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00   K...............
7fb5733e1818  01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................

Question

I'm curious why the shared library size discrepancy between disk versus memory?


Solution

  • As a variant, it could use rather large .bss section (uninitialized static and global variables).

    For example, function

    void foo(char * dst, size_t len)
    {
        static char table[4096];
        static int initialized;
    
        if (!initialized)
        {
            for (size_t i = 0; i < sizeof table; i++)
                table[i] = rand();
            initialized = 0;
        }
    
        for (size_t i = 0; i < length; i++)
            dst[i] &= table[i % sizeof(table)];
    }