c - 没有 printf() 返回 char 数组失败

标签 c return

我有一个程序,它接受用户输入,将该用户输入作为参数发送给进行计算的函数,然后将 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/

相关文章:

c - 错误 : lvalue required in this simple C code?(三元赋值?)

c++ - 将 void * 指向 char 作为 int 读取有多安全?

r - 从 R 中的函数中捕获警告并仍然获得它们的返回值?

java - 为什么在使用 if-else 且满足所有可能的条件时需要在方法中添加额外的 return 语句

Python `yield from` ,还是返回一个生成器?

c - Bool 函数在不满足条件的情况下返回 true - 忽略 printf()

c - 返回语句、值——它们是如何使用的?

c - Putchar 字符出现在我的 printf 函数的前面

将 c 顺序转换为 OpenMP 问题

谁能告诉我为什么这个无限的 while 循环不能正常工作?