我正在尝试查找数字的哈希并使用strcpy()复制到字符串,但复制操作无法正常工作。 这是我的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <openssl/sha.h>
#define DIGEST_LENGTH 4
unsigned char *perform_hash(unsigned char *string){
unsigned char *temp_hash = NULL;
unsigned char digest[DIGEST_LENGTH], mdString[DIGEST_LENGTH*2+1];
int i = 0;
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, string, strlen(string));
SHA1_Final(digest, &ctx);
for (i = 0; i < DIGEST_LENGTH; i++)
sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
printf("SHA1 digest{%s}: %s\n",string,mdString);
temp_hash = mdString;
printf("\nRET HASH:::%s",temp_hash);
return temp_hash;
}
void main(){
char *temp = NULL;
unsigned char *hash_nonce = (unsigned char *)malloc(sizeof(unsigned char)* 50);// FREEEEEE
memset(hash_nonce, 0,50);
temp = perform_hash("7c1824c5");
strcpy(hash_nonce,temp);
printf("\nHASH_NONCE:::%s\n",hash_nonce);
temp = NULL;
}
输出:
SHA1摘要{7c1824c5}:c79851b5
RET HASH ::: c79851b5
HASH_NONCE ::: 9
使用strncpy()代替strcpy()
函数strncpy(hash_nonce,温度,strlen的(温度));
输出:
SHA1摘要{7c1824c5}:c79851b5
RET HASH ::: c79851b5
HASH_NONCE :::
答案 0 :(得分:1)
ECHO OFF
IF (%1)==() goto Start
SET fromMSBuild=1
:Start
ECHO fromMSBuild:%fromMSBuild%
REM ***** Perform your actions here *****
set theExitCode=101
GOTO End
:End
IF %fromMSBuild%==1 exit %theExitCode%
REM **** Not from MSBuild ****
ECHO Exiting with exit code %theExitCode%
exit /b %theExitCode%
temp_hash = mdString;
是一个局部变量,一旦函数结束就超出了范围。当你的生命时间超过调用未定义的行为时,你正在访问它。(你在mdString
中访问它)摆脱这个分配动态内存。
strcpy()
动态分配后进行适当的检查,并在处理完毕后将其释放。