我有一个程序,它接受用户输入,将该用户输入作为参数发送给进行计算的函数,然后将char数组返回到main()函数以便在那里输出。
运行return (char *)&buf;
语句时printf()
正常工作。
但是,如果没有printf()
,则返回似乎不起作用,因为main()
函数无法输出返回的值。
以下是代码:
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
using namespace std;
char* hash_function(char* input_string)
{
int i = 0;
unsigned char temp[SHA_DIGEST_LENGTH]; //where we will store the SHA digest. length = 20
char buf[SHA_DIGEST_LENGTH*2];
memset(temp, 0x0, SHA_DIGEST_LENGTH); //array of size 20 to store SHA1 digest
memset(buf, 0x0, SHA_DIGEST_LENGTH*2); //array of size 2*20 to store hex result?
SHA1((unsigned char *)input_string, strlen(input_string), temp);
for(i=0; i<SHA_DIGEST_LENGTH; i++){
sprintf((char*)&(buf[i*2]), "%02x", temp[i]);
//element in temp[i] formatted with %02x and stored in buf[i*2]
}
//printf("In FUNCTION: %s\n", buf); //*************************************
return (char *)&buf;
}
int main(int argc, char * argv[])
{
if(argc != 2)
{
printf("Usage: %s <string>\n", argv[0]);
return -1;
}
char *hash = hash_function(argv[1]);
printf("Plaintext:\t%s\nSHA-1:\t\t%s\n\n", argv[1], hash);
//FILE *file = fopen("temp_file.txt", "a+"); //open file to write to
//fprintf(file, "Plaintext: %s\nSHA-1: %s\n\n", argv[1], buf);
return 0;
}
我用星号标记的行是我所指的print()
行。
为了编译,请使用g++ [file_name] -lcrypto -o [output]
您可能需要下载 openssl / sha.h 包。
答案 0 :(得分:0)
您正在返回指向堆栈上分配的缓冲区的指针。一旦hash_buffer返回,分配给buf的内存就会消失。您需要使用malloc在堆上分配buf。所以,改变你的功能:
char* hash_function(char* input_string)
{
int i = 0;
unsigned char temp[SHA_DIGEST_LENGTH]; //where we will store the SHA digest. length = 20
char *buf = NULL;
buf = malloc(SHA_DIGEST_LENGTH*2);
if (buf == NULL) {
return NULL;
}
memset(temp, 0x0, SHA_DIGEST_LENGTH); //array of size 20 to store SHA1 digest
memset(buf, 0x0, SHA_DIGEST_LENGTH*2); //array of size 2*20 to store hex result?
SHA1((unsigned char *)input_string, strlen(input_string), temp);
for(i=0; i<SHA_DIGEST_LENGTH; i++){
sprintf((char*)&(buf[i*2]), "%02x", temp[i]);
//element in temp[i] formatted with %02x and stored in buf[i*2]
}
return buf;
}