2

I am attempting to encrypt a string at compile-time, but the string seems to still be present in the data of my executable.

I disabled all optimizations, but yet it is still there

class str {
public:
    template<unsigned int Size>
    constexpr str(wchar_t(&String)[Size], wchar_t KeyCharacter)
        : m_Buffer{}, m_Key{}, m_Size{} {
        this->m_Size = Size;
        this->m_Key = KeyCharacter;
        this->SetString(String);
    }
    ~str() {

    }
    template<unsigned int Size>
    constexpr void SetString(wchar_t(&String)[Size]) {
        for(unsigned int i{}; i < this->m_Size; ++i) {
            this->m_Buffer[i] = String[i] ^ this->m_Key;
            String[i] = L'\0';
        }
        this->m_Buffer[this->m_Size] = L'\0';
    }
    constexpr wchar_t* GetString() {
        return this->m_Buffer;
    }
    wchar_t m_Buffer[250];
    wchar_t m_Key;
    unsigned int m_Size;
};

int main() {
    wchar_t unstr[] = { L"Hello, world!" };
    str s(unstr, L'a');
    getchar();
    return 0;
}

BTW, the code does not evaluate into a memcpy call, that's just the pseudocode's interpretation

pseudocode

As you can see, the hello world text is still there, but in the SetString function I empty it out. It is empty at run-time, but it still appears in the binary.

What is going on here? Why is the string still there? How can I fix it?

orORorOR
  • 133
  • 7
  • *at compile-time* - You should've used `constexpr str dds{unstr, L'a'};` – user7860670 Jun 27 '20 at 14:52
  • Are you sure you can constexpr a class instance? My compiler is not letting me – orORorOR Jun 27 '20 at 14:55
  • @orORorOR: You need to get rid of your meaningless destructor. – Davis Herring Jun 27 '20 at 15:23
  • If I make it a constepxr, the parameter will have to be const and then I cannot overwrite it – orORorOR Jun 27 '20 at 15:29
  • You say you've disabled all optimisations, but - practically - a compiler is likely to evaluate more at compile time if all optimisations are enabled. Also, "evaluation at compile time" and "don't output program data to the executable even if the only thing done with it is passing it to a `constexpr` function" are not the same thing. Compilers are often reticent about removing program data unless optimising for executable size anyway, since the effect is not observable when executing the program. – Peter Jun 27 '20 at 15:35
  • So how should I go about doing this then if not with constexpr? There's already working projects out there that do string encryption at compile-time, but mine does not seem to work – orORorOR Jun 27 '20 at 15:38
  • your string has to be const or it has to be somwhere in the code, because it is not const the compiler cannot know if there is anything else which could change the string so it has to use the function at runtime. – just a guy Jun 27 '20 at 16:32

0 Answers0