A. Neo
A. Neo

Reputation: 113

Why am I getting random outputs from this string to char conversion?

I'm just trying to do a string conversion to char (more precisely char*) but for no reason, I got different outputs if I run the code on codeBlocks or in my project. So on codeBlocks, I run this :

#include <iostream>
#include <string>

using namespace std;

int main()
{
    std::string stlstring = "abc";
    std::cout << stlstring << std::endl;
    char* writable = new char[stlstring.size() + 1];
    std::copy(stlstring.begin(), stlstring.end(), writable);
    writable[stlstring.size()] = '\n';
    std::cout << writable ;
}

I got this output : enter image description here

And in my project, I run the same lines but in an event handler :

void RePROGUIUser::applyOptions(wxCommandEvent& event) {
    std::string stlstring = "abc";
    std::cout << stlstring << std::endl;
    char* writable = new char[stlstring.size() + 1];
    std::copy(stlstring.begin(), stlstring.end(), writable);
    writable[stlstring.size()] = '\n';
    std::cout << writable;
}

Output :enter image description here

So I have to push a button on my GUI for that to happen but it really shouldn't change anything (and I was skeptical about putting the wxWidget tag here).

Any idea someone ?

Upvotes: 1

Views: 66

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

You code has undefined behavior, means anything is possible. Note that the null terminator is '\0' but not '\n'. So change

writable[stlstring.size()] = '\n';

to

writable[stlstring.size()] = '\0';

Upvotes: 6

Related Questions