2017-04-26 69 views
0

我有一个程序来通过用户输入,发送该用户输入作为一个参数传递给函数,这使得计算,则该字符数组返回到主()函数将要输出那里。返回char数组失败,且不printf()的

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包。

+1

'使用命名空间std;'是不是C. –

+3

'buf'成为功能之外无效。 – BLUEPIXY

+0

请不要期望评论者“下载openssl/sha.h包”。 –

回答

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; 
} 
+0

我读到另一个线程这表明这一点,但海报。被告知,这是不好的做法,因为它不清楚谁应该被允许释放这个记忆,那个保留的或另一个记忆呢?我会和它一起去的,我只是希望找到一个更“正确”的方式去解决它。 – Tawm

+1

这是在功能分配内存,并期望调用程序释放它可以接受的做法。 – bruceg

+0

为了提高稳健性,你可以通过初始化'temp',并使用'calloc'用于替代memset的调用'buf' –

相关问题