Reputation: 101
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!
Upvotes: 2
Views: 25640
Reputation: 109532
A bit much is wrong here.
dInt = strlen(input) + 1; // dInt is the size of the string including the terminating '\0'.
strlcpy
indeed uses the size, not strlen.
msg = tmp; and not freeing tmp. As msg is const char* "" (in C++ terms).
Upvotes: 0
Reputation: 8805
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 bl
function 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 frankly blake512_hash
shouldn't return uint8_t
array in the first place if you are expecting char
array as the output all the time), you could simply call msg[k] = (char)tmp[k]
in your for loop and remove memcpy
.
Upvotes: 7