2012-03-07 87 views
1

我是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

您正在将指针递增int的大小。那是错的。如果您想将数组置零,您将按char的大小进行增加。更好的是,只需使用memset

+0

所以我怎么能增加一个字符的大小?我认为编译器会为我做这件事,显然我错了。我将研究如何使用memset。 – tpar44 2012-03-07 21:44:39

+0

Memset做到了!谢谢! – tpar44 2012-03-07 21:57:03

+0

@ tpar44:您正在将'raw_sk'投射到'int *'。指针算术知道如何增加指针的类型。例如,向char指针加1会使指针增加1个字节。向int指针加1会增加4个字节(大部分时间)。我们可以概括这一点,并且说* * * *类型的指针增加* n *会使指针增加'n * sizeof(x)'。所以,如果你把'raw'_sk'改成'char *',那就没问题了。当然,实现它的惯用方法是创建一个临时指针,并简单地增加该指针,而不是添加“count”变量。 – 2012-03-07 22:10:37

0

你的循环迭代总size*sizeof(int)字节(其中最有可能sizeof(int)==4),但数组只有size字节大。因此,分段错误。

0

我想你的意思做

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

,因为我认为raw_sk指向字符数组

指针arithmatic的工作原理是在这种情况下,移动的类型的大小的内存地址,所以你要烧焦