Initially I want to convert this uint8_t array to a char array in c. I have been a little stuck trying to resolve this problem. My first alternative solution is to copy another type value to the temporary one, copy the tmp value to a writable char, and then remove tmp value from memory. By the way this is used to accompany a blake hash function. Here is my code snippet:
char * bl(char *input)
{
uint8_t output[64];
char msg[]= "";
char *tmp;
int dInt;
memset(output,0,64);
tmp = (char*) malloc(64);
if (!tmp){
exit( 1);
}
dInt = strlen(input);
if (dInt > 0xffff){
exit( 1);
}
uint8_t data[dInt];
memset(data,0, dInt);
strlcpy(data,input,dInt);
uint64_t dLen =dInt;
blake512_hash(output, data,dLen);
int k;
for (k=0;k<64;k++){
tmp[k] = output[k]; //does this "copy" is buggy code?
}
memcpy(msg, tmp,64);
//so here I can to delete tmp value
// I dont want there were left unused value in memory
// delete tmp;
free(tmp);
return msg;
}
I think the code above is still not efficient, so what are your opinion, hints and the fixes?
Thank you very much before!
First of all, you should never return a pointer to a local variable since the variable will be destroyed by the time the function exits. You should probably want to pass the output array to
blfunction and use that to output the string.For most cases(if uint8_t IS char, which is usually the case),
memcpy(msg, output, 64)should be sufficient. If you want to be strict about it(quite franklyblake512_hashshouldn’t returnuint8_tarray in the first place if you are expectingchararray as the output all the time), you could simply callmsg[k] = (char)tmp[k]in your for loop and removememcpy.