我是 C 编程新手,我对指针数学感到困惑。我有一个大小为 32 的字符数组。据我了解,这意味着该数组也是 32 个字节,因为字符变量因此是 1 个字节大32 characters * 1 byte = 32 bytes
。问题是当有一个函数有一个指向前面描述的字符数组的空指针时。我相信代码段
for (count = 0; count < size; count++)
*((int*) raw_sk + count) = 0
应该将 raw_sk 缓冲区中的所有插槽都设置为 0。但是,当我运行程序时,我遇到了分段错误。我认为这可能是我在地址中添加计数的事实。我想如果我要向地址添加一个,我将移动到数组中的下一个插槽。有人可以指出我哪里出错了吗?我正在使用的功能如下。谢谢!
void
write_skfile (const char *skfname, void *raw_sk, size_t raw_sklen)
{
int fdsk = 0;
char *s = NULL;
int status = 0;
int count = 0;
int size = (raw_sklen);
/* armor the raw symmetric key in raw_sk using armor64 */
s = armor64(raw_sk, raw_sklen);
/* now let's write the armored symmetric key to skfname */
if ((fdsk = open (skfname, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) {
perror (getprogname ());
/*scrubs the armored buffer*/
for(count = 0; count < armor64len(s); count++)
s[count] = '0';
free (s);
/* scrub the buffer that's holding the key before exiting */
for (count = 0; count < size; count++)
*((int*)raw_sk + count) = 0;
exit (-1);
}
else {
status = write (fdsk, s, strlen (s));
if (status != -1) {
status = write (fdsk, "\n", 1);
}
for (count = 0; (size_t)count < 22; count++)
*((int*)raw_sk + count) = 0;
free (s);
close (fdsk);
/* do not scrub the key buffer under normal circumstances
(it's up to the caller) */
if (status == -1) {
printf ("%s: trouble writing symmetric key to file %s\n",
getprogname (), skfname);
perror (getprogname ());
/* scrub the buffer that's holding the key before exiting */
/* scrub the buffer that's holding the key before exiting MY CODE
for (count = 0; count < size; count++)
*((int*)raw_sk + count) = 0;*/
exit (-1);
}
}
}