Reputation: 61
I have a snippet of code below that appends the text _dut1_serial_log.txt
to a supplied filename. The supplied filename is a variable in the struct pointed to by targetP
.
The text _dut1_serial_log.txt
is 20 chars long. My question is do I need the +1
when I call malloc for the null terminator?
char *filename_ending = "_dut1_serial_log.txt";
char *filename_with_extension;
prv_instance_t *targetP = threadParams->targetP;
/*append filename ending "_dut1_serial_log.txt" to filename supplied*/
filename_with_extension = malloc(strlen(targetP->output_filename)+1+20);
strcpy(filename_with_extension, targetP->output_filename); /* copy name into the new var */
strcat(filename_with_extension, filename_ending); /* add the extension */
Upvotes: 2
Views: 1784
Reputation: 234715
Both strcpy
and strcat
will copy the NUL-terminator from the source string to the destination buffer.
You do need to reserve space for that terminator in the destination buffer therefore.
To avoid any doubt, "_dut1_serial_log.txt"
is a const char[21]
type.
Upvotes: 2