I am maintaining a piece of C code where char arrays are frequently populated by passing them into functions and using the result as a string that is written to output. However there is no checking done on the array after it has been processed by the function and I'm wondering what the best approach to take is?
One approach is to set the last element in the array to \0 after it has been returned but I suspect there are probably better ones.
void Unpack(char* inbuf, char* outbuf);
int main(int argc, char* argv[])
{
char* inData = "abc";
char outData[4];
char result[14];
Unpack(inData, outData);
outData[3] = '\0'; // Insert this to safeguard array before using as string.
_snprintf(result, sizeof(result), "blah %0s blah", outData);
printf(result);
return 0;
}
void Unpack(char* inbuf, char* outbuf) {
for(int index=0; index<3; index++) {
*outbuf++ = *inbuf++;
}
}