双重免费或腐败(fasttop)

时间:2017-02-10 12:30:09

标签: c memory-management

大家好我有像这样的数组调整大小功能

int
add_time_element (time_t *array, time_t element, size_t *size)
{
    if (NULL == array)
    {
        return STATUS_FAIL;
    }

    int status = STATUS_SUCCESS;
    time_t *tmp = NULL;
    size_t local_size;

    (*size)++;
    local_size = *size;

    printf ("Local size %lu\n", local_size);

    tmp = realloc (array, local_size * sizeof (time_t));
    if (NULL == tmp)
    {
        status = STATUS_FAIL;   
    }
    else 
    {
        array = tmp;
    }

    if (STATUS_FAIL == status)
    {   
        (*size)--;
    }
    else
    {
        array[local_size - ONE] = element;
    }

    return status;  
}

我这样称呼这个函数..

  time_t *dates = NULL;
    dates = malloc (ONE);
    for (slot_index = ZERO; slot_index < data_provider->n_slots; slot_index++)
    {
        printf ("Testing\n");
        /*slot = data_provider->slots[slot_index];
        date = get_date (slot->start_time);*/
        date += ONE;    
        if (STATUS_FAIL ==  add_unique_time_element (dates, date, &n_dates))
        {
            free (dates);
            dates = NULL;   
            return STATUS_FAIL;
        }
    }

我在realloc函数中遇到双重自由(fasttop)错误..

valgrind分析报告说

Invalid free() / delete / delete[] / realloc()
==22491==    at 0x4C2DD9F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22491==    by 0x402BA3: add_time_element (array_util.c:353)
==22491==    by 0x402C6C: add_unique_time_element (array_util.c:399)
==22491==    by 0x401F92: create_dates (data_provider.c:283)
==22491==    by 0x401D7D: create_data_provider_file (data_provider.c:174)
==22491==    by 0x4075CC: main (data_provider_test.c:13)
==22491==  Address 0x5b63170 is 0 bytes inside a block of size 1 free'd
==22491==    at 0x4C2DD9F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22491==    by 0x402BA3: add_time_element (array_util.c:353)

请帮忙。

1 个答案:

答案 0 :(得分:1)

你的功能原型是

int add_time_element (time_t *array, time_t element, size_t *size)

您在例程中更改了array,但它没有反映在来电者身上,您正在更改array指针的副本

所以,下次你打电话给你的例行公事时,如果array已经被realloc更改,因为它需要更大的尺寸(没有系统地发生),你就是这样做了传递一个已经释放的指针。

可能的修复:

  • 返回array而不是您的状态(如果失败则返回NULL
  • array作为time_t **array传递,并在日常工作中将其称为*array(并使用&array致电)

(第一种选择更简单)

注意:代码的其余部分在错误处理方面写得非常好(具有讽刺意味的是)