我有一个程序,它接受用户输入,将该用户输入作为参数发送给进行计算的函数,然后将 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 软件包。
最佳答案
您正在返回一个指向堆栈上分配的缓冲区的指针。一旦 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;
}
关于c - 没有 printf() 返回 char 数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43645894/