我是C编程的新手,我对指针数学感到困惑。我有一个大小为32的字符数组。我的理解是,这意味着数组也是32字节的,因为字符变量是1字节长,因此是32 characters * 1 byte = 32 bytes。问题是,当一个函数有一个空指针指向一个字符数组时,如前所述。我相信代码段
for (count = 0; count < size; count++)
*((int*) raw_sk + count) = 0应设置raw_sk缓冲区中的所有插槽均应设置为0。然而,当我运行这个程序时,我得到了一个分段错误。我想这可能是因为我将计数加到了地址上。我想,如果我将一个地址加1,我将移动到数组中的下一个位置。有没有人能指出我哪里错了?下面是我正在使用的函数。谢谢!
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);
}
}
}发布于 2012-03-08 05:41:35
您将按int的大小递增指针。这是错误的。如果您想将数组置零,则可以按char的大小递增。更好的是,只使用memset。
发布于 2012-03-08 05:40:10
您的循环总共迭代了size*sizeof(int)字节(其中最有可能是sizeof(int)==4),但是数组只有size字节大小。因此,分段错误。
发布于 2012-03-08 05:43:18
我想你是故意的
*((char*) raw_sk + count) = 0因为我假设raw_sk指向char数组
指针算法的工作原理是根据类型的大小移动内存地址,因此在这种情况下,您需要
https://stackoverflow.com/questions/9609428
复制相似问题