Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cout string print its memory value

Tags:

c++

string

cout

I am trying to create a keygen to some reversing challenges around there. I decided to try to code it in a language that I don't know well, c++

I not sure how to use pointers yet, but I thing that I implemented the algorithm well without them. the only problem is that I print the answer I get it's memory location instead all the string.

char decrypt(char c, int position);
int main(){

    cout << "Enter username:" << endl;
    string username;
    string answer[20] = "";
    cin >> username;
    for (int i = username.length(); i > 0; i--){
        answer[username.length() - i] = decrypt(username[i-1],i);
        if (i == 0){
            answer[username.length() +1] = '\0';
        }
    }
    return 0;
}
char decrypt(char c, int position)
{
    if (position == 4){
         return '-'; }
    if (c > 'M'){
        c -= 17;    }
    else{
        c += 21;    }
    c ^= position;
    c ^= 2;
    return c;
}

If I will try to print the string username I will get the string and not the memory location of username. So I'm not sure what is going on.. Thanks for any help, Or

like image 450
Smiled_One Avatar asked Aug 08 '26 21:08

Smiled_One


2 Answers

First, try to use the answer variable as a string and not a char*. A string authomatically resize and realocates its internal buffer if needed.

The code could looks like this:

string username;
string answer;
cin >> username;
for (int i = 0; i < username.length(); i++)
{
    answer += decrypt(username[i],i+1);
}

Then if you want to see the content of the internal string buffer, you can use answer.c_str ();

Edit:

As songyuanyao said, your code uses an array of string. But the solution of using an array of 20 chars (char answer [20]) leads to a memory issue if the username has a size of 20 or more.

like image 120
S.Clem Avatar answered Aug 11 '26 12:08

S.Clem


If I understand your question correctly,

string answer[20] = "";

should be

char answer[20];

string answer[20] is array of std::string, not the c-style string (i.e. char[]).

like image 38
songyuanyao Avatar answered Aug 11 '26 11:08

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!