Memory is still available bug fixed, but why?

I am experimenting with shared libraries to create a modular program.

There are two cpp files to compile:

Shared library, compile with

g ++ -fPIC -shared module.cpp -o module.so

//module.cpp #include <iostream> 

File using a shared library, compile with

g ++ src / main.cpp -ldl -o binary

or

g ++ -DFIX src / main.cpp -ldl -o binary

 //main.cpp #include <dlfcn.h> #ifdef FIX # include <iostream> #endif int main() { void* h = dlopen("./module.so", RTLD_LAZY); if ( h ) { dlclose(h); } } 

With FIX undefined, valgrind reports a lot of available memory (5373 bytes), no memory leak occurs when defining FIX .

What is the problem with using iostream in shared libraries?

This problem occurs with g ++ - 4.6, g ++ - 4.7 and g ++ - 4.8. g ++ - 4.4 does not show this behavior. I have no other compilers for testing, unfortunately (and I don't want to switch to g ++ - 4.4 because of this).

Update:

Compiling a shared library file with the additional flags -static-libstdc++ -static-libgcc reduces the number of leaked blocks, but not completely. -static-libgcc alone has no effect, -static-libstdc++ has some effect, but not as much as the one.

+6
source share
1 answer

1. Why or how does this piece of code “fix” the problem?

I'm not sure why, without breaking into the libstdC ++ code, but I assume that the memory allocated by the iostreams library, which is stored throughout the program, is reported as a valgrind problem when it is allocated in the shared library, but not when assigned to the main the program.

2. What equivalent, independent (from the standard library) code fragment provides the same error correction?

Firstly, I don’t know why you want something “independent of the standard library” when the available memory is still probably allocated by the standard library. The fix is ​​either that you are not using the standard library at all, anywhere or using it differently.

Secondly, this “fix” is undefined behavior because you violate the rule of one definition by overriding std::ios_base differently to the correct definition in std lib.

The correct way to get the same behavior is #include <iostream> in your main.cpp file, including <iostream> defines a static std::ios_base::Init object. Alternatively, simply #include <ios> , and then define a static variable (but do not override the std::ios_base ), but basically what <iostream> does, so you can also use this.

+1
source

Source: https://habr.com/ru/post/955260/


All Articles