【发布时间】:2013-12-26 06:24:03
【问题描述】:
我在c++中有以下函数
char* Test::convertToSHA(const char* cc) {
const char* salt ="sh$^$#@!&7hbfvatfacv@@@@bagg=shjgvshvcbschj";
time_t currentTime;
time(¤tTime);
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;
}
在通话中我使用
char* output=NULL;
output= Test::convertToSHA("hello");
这导致我的代码崩溃。我返回字符串有问题吗?我怎样才能从这个函数返回?
【问题讨论】:
-
这应该只返回一个
std::string。 -
不返回堆栈变量。要么
new hexstring,要么让调用者分配内存并传递给convertToSHA。但更好的方法是返回 std::string (或通过引用返回),因为您使用的是 c++。 -
你能告诉我怎么做吗?
-
调用者不知道要分配多少内存?
-
您为什么要创建(并忘记填充)临时缓冲区
str?你可以写sha1::calc(s.data(), s.length(), hash);。