Search code examples
c++ubuntupthreadsvalgrindubuntu-20.04

static link pthread on ubuntu causes uninitialised value jumps (valgrind)


When im statically linking the pthread library on ubuntu 20.04, using the gcc 11.1 compiler, during its runtime, my program works exactly as expected. However when i tried to run it in a debug mode and check with valgrind for any problems, i quickly discovered that linking the pthread library causes a lot of warnings to pop up. Why is that and is it something i should be worried about? (both std::thread and std::jthread display the same errors).

If i don't link the library statically, there are no errors or warnings.

main.cpp:

#include <iostream>
#include <thread>

void foo() {
    std::cout << "Hello world" << std::endl;
}

int main() {
    std::jthread t(foo);
    return 0;
}

Compile:

g++ main.cpp -std=c++20 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

The way im linking the pthread lib i took from here. Otherwise i'd get a segfault.

Sample of the errors i'm getting:

==9674== Syscall param set_robust_list(head) points to uninitialised byte(s)
==9674==    at 0x404E65: __pthread_initialize_minimal (nptl-init.c:272)
==9674==    by 0x4B858E: (below main) (in /home/example)
==9674==  Address 0x4000bf0 is in the brk data segment 0x4000000-0x400123f
==9674== 
==9674== Conditional jump or move depends on uninitialised value(s)
==9674==    at 0x4F5780: __register_atfork (in /home/example)
==9674==    by 0x4F574C: __libc_pthread_init (in /home/example)
==9674==    by 0x405056: __pthread_initialize_minimal (nptl-init.c:368)
==9674==    by 0x4B858E: (below main) (in /home/example)
==9674== 
==9674== Conditional jump or move depends on uninitialised value(s)
==9674==    at 0x4F5804: __register_atfork (in /home/example)
==9674==    by 0x4F574C: __libc_pthread_init (in /home/example)
==9674==    by 0x405056: __pthread_initialize_minimal (nptl-init.c:368)
==9674==    by 0x4B858E: (below main) (in /home/example)
==9674== 
==9674== Conditional jump or move depends on uninitialised value(s)
==9674==    at 0x4FA870: malloc_hook_ini (in /home/example)
==9674==    by 0x5759DA: _dl_get_origin (in /home/example)
==9674==    by 0x5495F4: _dl_non_dynamic_init (in /home/example)
==9674==    by 0x54BF45: __libc_init_first (in /home/example)
==9674==    by 0x4B85C8: (below main) (in /home/example)

and it goes on and on about uninitialised values.


Solution

  • If i don't link the library statically, there are no errors or warnings.

    Linking libpthread or libc on Linux statically is almost always the wrong thing to do. Your executable may be broken in many subtle ways, if not now then in the future.

    That said, the reason you get Valgrind errors is explained here.