使用数组的指针算法

时间:2012-03-07 21:34:52

标签: c pointers segmentation-fault pointer-arithmetic

我是C编程的新手,我对指针数学感到困惑。我有一个大小为32的字符数组。我的理解是,这意味着数组也是32个字节,因为字符变量大1个字节,因此32 characters * 1 byte = 32 bytes。问题是当一个函数有一个指向一个字符数组的void指针时,如前所述。我相信代码段

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);
    }
  }
}

3 个答案:

答案 0 :(得分:3)

您正在将指针递增int的大小。那是错的。如果要将数组清零,则按char的大小递增。更好的是,只需使用memset

答案 1 :(得分:0)

您的循环总共迭代size*sizeof(int)个字节(最可能是sizeof(int)==4),但该数组仅大size个字节。因此,分段错误。

答案 2 :(得分:0)

我认为你打算这样做

*((char*) raw_sk + count) = 0

因为我假设raw_sk指向char数组

指针算术通过按类型大小移动内存地址来工作,所以在这种情况下你需要char