0

I have the following function in c++

    char* Test::convertToSHA(const char* cc) {

    const char* salt ="sh$^$#@!&7hbfvatfacv@@@@bagg=shjgvshvcbschj";
    time_t currentTime;
    time(&currentTime);
    CCString startTimeString;
    startTimeString.createWithFormat("%d", currentTime);

    std::string s = cc;
    s += startTimeString.getCString();
    s += salt;

    char *str = new char[strlen(s.c_str()) +  1];
    int length=strlen(str);
    unsigned char hash[length*2];
    char hexstring[41];
    sha1::calc(str,length,hash);
    sha1::toHexString(hash, hexstring);

    return hexstring;
}

And in the call i use

char* output=NULL;
output= Test::convertToSHA("hello");

This is causing my code to crash. Is there a problem with me returning a string ? How can i return from this function ?

Ray
  • 2,472
  • 18
  • 22
AndroidDev
  • 15,993
  • 29
  • 85
  • 119

2 Answers2

5

You can never return a local pointer in C or C++. Instead, either pass the pointer as a parameter:

void Test::convertToSHA(const char* cc, const char* hexstring) {

   //no change to body
   //no return statement needed
}

//then when calling the function:

char hexstring[41];

convertToSHA(cc, hexstring);

//hexstring has been modified

Or just use std::string instead. Use the c_str() if you need to convert to a c-style string (you still can't return the pointer, though).

Community
  • 1
  • 1
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
3

I'm assuming you're using this library. I find it odd that it claims to be written in C++ but doesn't take advantage of C++ idioms. The function modifies the pointer, and doesn't return anything, so you do need a local variable. Lucky for you, std::strings will happily accept a char [] argument.

std::string Test::convertToSHA(const char* cc) {
    // ...
    char hexstring[41];
    sha1::calc(str,length,hash);
    sha1::toHexString(hash, hexstring);
    std::string ret(hexstring);

    return ret;
}