c malloc() - 我是否需要为空终止符分配 space

c malloc() - do I need to allocate space for the null terminator

我在下面有一段代码,将文本 _dut1_serial_log.txt 附加到提供的文件名中。提供的文件名是 targetP 指向的结构中的一个变量。

文本 _dut1_serial_log.txt 的长度为 20 个字符。我的问题是当我为空终止符调用 malloc 时是否需要 +1

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 */

strcpystrcat 都会 将 NUL 终止符从源字符串复制到目标缓冲区。

因此,您确实需要在目标缓冲区中为该终止符保留 space。

为了避免任何疑问,"_dut1_serial_log.txt"const char[21] 类型。