JustasMasiulis / xorstr

heavily vectorized c++17 compile time string encryption.
Apache License 2.0
1.19k stars 193 forks source link

Incorrect string in gcc release mode #26

Closed BullyWiiPlaza closed 4 years ago

BullyWiiPlaza commented 4 years ago

With optimizations enabled using gcc version 9.2.1 (-O3 flag) on Ubuntu the following code produces an incorrect output:

#include <iostream>
#include "xorstr.hpp"

int main() {
    const auto decrypted_string = xorstr_("Hello, world!");
    std::cout << decrypted_string << std::endl;

    return EXIT_SUCCESS;
}

Output: � a6�2F���!%��E�E���

Decompiled: image

In debug mode the code correctly outputs: Hello, world!

Decompiled: image


Interestingly, in MSVC it works fine either way.

Decompiled debug build: image

Decompiled release build: image

JustasMasiulis commented 4 years ago

you are printing a dangling pointer

xorstr_ is the same as xorstr(...).crypt_get() which returns a pointer to the internal buffer.

BullyWiiPlaza commented 4 years ago

@JustasMasiulis Ah. So inlining the variable fixes it?

int main() {
    std::cout << xorstr_("Hello, world!") << std::endl;
    return EXIT_SUCCESS;
}

Now it works correctly. Damn. This is dangerous to accidentally mess up.

JustasMasiulis commented 4 years ago

yeah, that would be how you would most commonly use it, although it's entirely possible to store it and use it multiple times

auto xs = xorstr("something);
puts(xs.crypt_get());
puts(xs.get());