双重免费或损坏错误

时间:2013-12-04 15:14:16

标签: c

我一直收到这个错误:

*** glibc detected *** /s/httpget: double free or corruption (fasttop): 0x00000000005352a0 ***

我真的没有看到,我有两次免费。所以我猜是因为腐败...... 我在附带的代码中做了一些评论,所以请看一下,以便更好地理解问题。

Here backtrace:
#5  0x0000000000401077 in processXML (
    start=0x506010 "<I k=\"506012,148,1\" b=\"158\" n=\"11393\" \n</I>\n<I k=\"2553367,257,814\" b=\"2781\" n=\"43020\"                                                                                    "1\" td=\"15\" d=\"20131204\" t=\"144734\" z=\"110\">\n<P k=\"33,3,0\" gn=\"1\" v=\"18.65\"/>\n<P k=\"33,3,1\" v=\"18.65                                                                                   >\n</I>\n<I "..., stop=0x50af1a "<I k=\"506012,148,1\" b=\"158\" n=\"11393\" ", t=0x51ecb0) at cli.c:178
#6  0x0000000000401669 in main () at cli.c:292

这里是代码:

void processXML(char *start, char *stop, GTree* t)
{
    if (start == NULL)return;
    start = strstr(start,START);
    char *  cp = start ;
    char * tmpP;
    gpointer* key;
    ticP tP;
    size_t  symlen=0;
    while (cp < stop)
    {
      //here the first occurance of the var, which causes the problem
      char * triP;
      cp  =  (strchr( cp, '"'))+1;
      tmpP = strchr( cp, '"');
      if ( tmpP != NULL )
      {
        symlen  = (tmpP - cp) ;
        printf("mallocated %zu\n", symlen) ;
        //EDIT
        triP = malloc(symlen+1);
        memcpy (triP, tmpP - (symlen) , symlen);
        triP [symlen]   = '\0';
        printf(">>VAL %s<<\n", triP);
        cp = strstr( cp, STARTP);
        if (cp == NULL){ return;}
      }
     if (triP != NULL && (key = g_tree_lookup (t, triP))== NULL )
     {
        printf("I N S E R T E D \n");
        tP = malloc(sizeof(tic));
        g_tree_insert(t, triP, tP);
     }
     //here I try to free it but only if some bytes were allocated...   
     if (symlen >0)free (triP);

有什么问题?

1 个答案:

答案 0 :(得分:6)

绝对腐败,是的。这样:

triP = malloc(symlen);
memcpy (triP, tmpP - (symlen) , symlen);
triP [symlen]   = '\0';

用最后一行破坏了未分配的空间。如果分配symlen个字节,则有效索引从0到(并包括)symlen - 1,但索引symlen超出分配的空间1个字节。吊杆。

像往常一样,要构建一个包含n实际可见字符的字符串,您需要n + 1个字符的空间,以包含终结符。