C base64解码功能:SIGSEGV,分段故障

C base64解码功能:SIGSEGV,分段故障,c,C,这是一个对base64进行解码的函数。SIGSEGV(有时是SIGABORT)发生在调用的malloc的行中。这几乎让我发疯!提前谢谢 static char base64_table[255] = {'\0'}; static void base64_tableinit() { int i,j; bzero(base64_table,255); for(j=0,i='A';i<='Z';i++) base64_table[i]=j++; for(

这是一个对base64进行解码的函数。SIGSEGV(有时是SIGABORT)发生在调用的malloc的行中。这几乎让我发疯!提前谢谢

static char base64_table[255] = {'\0'};

static void base64_tableinit()
{
   int i,j;
   bzero(base64_table,255);
   for(j=0,i='A';i<='Z';i++) 
       base64_table[i]=j++;
   for(i='a';i<='z';i++)
       base64_table[i]=j++;
   for(i='0';i<='9';i++)
       base64_table[i]=j++;

   base64_table['+']=j++;
   base64_table['/']=j++;
   base64_table['=']=j;
}    
char *decode(const char *cptr,char **rptr)
{
    if(cptr==NULL)
    {
        fprintf (stderr, "The input string is NULL!\n");
        exit(1);
    }

    int len = strlen(cptr);
    if(len%4 != 0)  
    {
        fprintf (stderr, "The input string length is not 4X!\n");
        exit(1);
     }

     base64_tableinit();
     int clen=len/4;

#ifdef DEBUG
    /// printf ("The length of string len = %d\n",len);
    /// printf ("The length of string clen = %d\n",clen);
#endif
    char* res = NULL;
    /// Error: below, SIGSEGV
    if((res=(char *)malloc((len-clen + 1) * sizeof(char)))==NULL)
    {
        fprintf (stderr, "Can't malloc enough space in decode!\n");
        exit(1);
    }

    for(*rptr=res; clen>0; clen--)
    {
        *res = base64_table[(int)*cptr++]<<2 ;              /* Use the 1th char(6) */
        *res++|= base64_table[(int)*cptr]>>4 ;               /* Use the 2th char(2) */ /// Construct the first char 

        *res = base64_table[(int)*cptr++]<<4 ;              /* Use the 2th char(4) */
        *res++ |= base64_table[(int)*cptr]>>2 ;             /* Use the 3th char(4) */  /// Construct the second char 


        *res = base64_table[(int)*cptr++]<<6;               /* Use the 3th char(2) */
        *res++ |= base64_table[(int)*cptr++]&0x3f;          /* Use the 4th char(6) */  /// Construct the third char 

    }
    *(res+len-clen) = '\0';

    return *rptr;
}

malloc
中的分段错误是一个相当肯定的迹象,表明发生了一些野生内存损坏,或者有人
free
s指向非动态分配内存的指针。这两个错误不一定发生在您显示的代码或触发
SIGSEGV
的代码中。 但是,这两种错误通常都是通过
valgrind
检测到的:

*(res+len-clen) = '\0';
似乎是错误的,因为您已经在整个循环中递增了
res
,所以它应该是

*res = '\0';

@sidyll很抱歉不清楚,刚刚编辑的这个最小样本是否能够重现问题?如果没有,您能提供一个吗?这是否意味着错误可能发生在其他地方,但gcc会在分配内存的位置报告错误?@LouXiou:
gcc
在这里不报告错误
gcc
完成了它的工作当它完成编译时,它与运行程序无关。程序崩溃,内存分配中断,而中断的分配可能位于代码中完全不同的位置。抱歉。。我是指gdb报告的回溯消息。
*res = '\0';