calloc char 数组和 null 终止字符之间的关系
Relation between calloc char array and null terminating character
网络上关于 strncpy
安全与不安全的整个 "debate" 快把我逼疯了。我发现有些人说 strncpy
是 "devil",在我看来他们缺乏编程纪律。我知道当 src
大于 dest
时 dest
的末尾没有添加 [=15=]
字符(这最终会导致问题)。我听说过 strlcpy
,但据我所知,它并不标准。我希望我的代码尽可能可移植,所以我认为这不是一个可行的解决方案。
这是我目前的解决方案...
首先定义缓冲区大小
#define BUFSIZE 1024
在程序中,使用calloc
分配缓冲区
char *buffer;
buffer = calloc(BUFSIZE+1, sizeof(char));
然后在代码的后面,假设我想将 msg
复制到 buffer
并且我使用
strncpy(buffer,msg,BUFSIZE);
因为我用 BUFSIZE + 1
预分配了 buffer
那么这确保了 buffer
的最后一个字节是 [=15=]
而不管 msg
是否大于 BUFSIZE
.
现在的问题是,calloc
是否用[=15=]
初始化字符数组?将calloc
的零分配解释为与[=15=]
相同是错误的吗?
清除数组 0
会将所有字符填充到 [=11=]
。
So '[=12=]' is completely equivalent to an unadorned 0 integer constant - the only difference is in the intent that it conveys to a human reader ("I'm using this as a null character.").
见What is the difference between NULL, '[=13=]' and 0
网络上关于 strncpy
安全与不安全的整个 "debate" 快把我逼疯了。我发现有些人说 strncpy
是 "devil",在我看来他们缺乏编程纪律。我知道当 src
大于 dest
时 dest
的末尾没有添加 [=15=]
字符(这最终会导致问题)。我听说过 strlcpy
,但据我所知,它并不标准。我希望我的代码尽可能可移植,所以我认为这不是一个可行的解决方案。
这是我目前的解决方案...
首先定义缓冲区大小
#define BUFSIZE 1024
在程序中,使用calloc
char *buffer;
buffer = calloc(BUFSIZE+1, sizeof(char));
然后在代码的后面,假设我想将 msg
复制到 buffer
并且我使用
strncpy(buffer,msg,BUFSIZE);
因为我用 BUFSIZE + 1
预分配了 buffer
那么这确保了 buffer
的最后一个字节是 [=15=]
而不管 msg
是否大于 BUFSIZE
.
现在的问题是,calloc
是否用[=15=]
初始化字符数组?将calloc
的零分配解释为与[=15=]
相同是错误的吗?
清除数组 0
会将所有字符填充到 [=11=]
。
So '[=12=]' is completely equivalent to an unadorned 0 integer constant - the only difference is in the intent that it conveys to a human reader ("I'm using this as a null character.").
见What is the difference between NULL, '[=13=]' and 0