【问题标题】:c malloc() - do I need to allocate space for the null terminatorc malloc() - 我需要为空终止符分配空间吗
【发布时间】:2017-12-05 11:09:55
【问题描述】:

我在下面有一个 sn-p 代码,它将文本 _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 */

【问题讨论】:

  • 是什么让你认为不需要为 NUL 终止符分配空间?
  • 如果不为其分配内存,则不允许存储。还有谁可以负责分配额外的内存?
  • 这很糟糕:filename_with_extension = malloc(strlen(targetP->output_filename)+1+20);。如果您将文件名从"_dut1_serial_log.txt" 更改为"mylongfilename_whatever.txt",会发生什么?写malloc(strlen(targetP->output_filename) + strlen(filename_ending) + 1);。或者更好:char filename_ending[] = "_dut1_serial_log.txt";malloc(strlen(targetP->output_filename) + sizeof(filename_ending));
  • @MichaelWalz 谢谢你的建议。非常感谢

标签: c string malloc null-terminated


【解决方案1】:

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

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

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

【讨论】:

  • "为避免任何疑问,"_dut1_serial_log.txt" 是一个 const char[21] 类型。",不是严格符合,但无论如何。
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
  • 2016-05-08
  • 2013-07-09
相关资源
最近更新 更多