0

I have made this function to extract the first 2 characters of a string:

string get_salt(string hash)
{
    char pre_salt[2];

    for (int i = 0; i < 2; i++)
    {
        pre_salt[i] = hash[i];
    }
    string salt = pre_salt;
    printf("%s\n", salt);
    return(salt);
}

But when I run it with a string that has "50" (is the example I'm using) as the first 2 characters, I get this output:

50r®B

And to be honest I have no idea why is it adding the 3 extra characters to the resulting string.

  • Is this C or C++? – Mark Nov 20 '19 at 23:58
  • Strings in C need to be NUL terminated. Make sure `pre_salt` is one larger than the number of characters and ensure last element is 0. – kaylum Nov 21 '19 at 00:02
  • Missing zero-terminator, also C doesn't have a "string" type, so a function can't return one. If you're using "string" as a synonym for "char*", then your function is returning a local that will go out of scope. – Lee Daniel Crocker Nov 21 '19 at 00:12
  • Just tried that adding a '\0' to the last element of the sting and worked out! I'm using a library that has the string data type into it so even though I'm using C, I'm able to pass string type variables to functions as inputs or outputs. I have a question, what's the difference of declaring a char* variable instead of a char variable? – Fernando Velasco Borea Nov 21 '19 at 00:47

1 Answers1

1

You are missing the string's NUL terminator '\0' so it keeps printing until it finds one. Declare it like:

char  pre_salt[3]={0,0,0};

And problem solved.

guilleamodeo
  • 270
  • 2
  • 10