C programming newbie here...
I have a function which does some maths and stores the result in an output variable:
void myFunction(char* output) {
unsigned char myData[64]={0};
// Call to another function which fills the 'myData' array
compute(myData);
// Now let's format the result in our output variable
for (int n=0; n<64; n++) {
sprintf(output, "%s%02x", myData[n]);
}
}
The output char array is allocated by the caller in a variable called result
:
void main(void) {
char* result = NULL;
result = malloc(129 * sizeof(unsigned char)); // twice the size of myData + 1 ending byte
myFunction(result);
// process result here
// (...)
free(result);
}
Problem is I always get some garbage stuff at the beginning of result
, for instance:
���˶ang/String;8fb5ab60ed2b2c06fa43d[...]
Here the expected data starts at 8fb5ab60ed2b2c06fa43d
. After doing some logs, I know that result
already contains ���˶ang/String;
before the sprintf() loop.
I don't understand how this can occur: isn't the malloc() function supposed to reserve memory for my variable? I guess this garbage comes from another memory area, which will eventually lead to some funky behavior...
That said, I've found a workaround just by adding a null ending byte at the 1st position of result
, before calling the function:
result[0]='\0'; // initialisation
myFunction(result);
Now it works perfectly but I highly doubt that's good practice... Any advice?