在C中为字符串动态分配内存时,是否计算字符串char的\ 0结尾?

时间:2012-03-08 00:46:33

标签: c string malloc calloc

在C中为字符串动态分配内存时,是否计算字符串char的\ 0结尾?

char *copyInto, *copyFrom="test";

// Should 
copyInto = (char*)malloc(strlen(copyFrom));
// suffice?

// or should this be the following?
copyInto = (char*)malloc(strlen(copyFrom)+1);

// assuming you want to copy the string from copyFrom into copyInto
strcpy(copyInto,copyFrom);

// Does anyone recommend just \0-ing the whole copyInto as in
copyInto = (char*)calloc(strlen(copyFrom)+1);
// and if so, should it still be (strlen(copyFrom)+1) size?

1 个答案:

答案 0 :(得分:6)

  1. 请勿在C程序中投放malloc()calloc()(或realloc()的返回值)。
  2. 是的,您需要拥有+1
  3. 如果您要立即复制整个字符串,为什么还要使用calloc()将整个字符串归零?对我来说似乎浪费了周期。