【问题标题】:Freeing void pointer array, crashes after freeing first element释放 void 指针数组,释放第一个元素后崩溃
【发布时间】:2017-04-13 19:50:49
【问题描述】:

我有这样一个简单的程序,它将void* 数组包装成一个具有长度和自动调整大小的结构。虽然在我释放第一个元素后它崩溃了。

Gif that illustrates my problem

#include "stdafx.h"
#include "array.h"
#include "error_handler.h"

#define RESIZE_STEP 3

Array * new_array(int initial_length, size_t size_of_element)
{
    Array* temp_struct = NULL;
    temp_struct = (Array*)malloc(sizeof(Array));
    void** temp_array = NULL;
    temp_array = (void**)malloc(initial_length * size_of_element);
    if (!temp_array) {
        if (print_message(MEMORY_ALLOCATION_ERROR) == BREAK)
        {
            deallocate_tab(temp_struct);
            temp_array = NULL;
            exit(1);
        }
    }

    for (int i = 0; i < initial_length; i++) {
        temp_array[i] = malloc(size_of_element);
        if (!temp_array[i] && print_message(MEMORY_ALLOCATION_ERROR) == BREAK) {
            deallocate_tab(temp_struct);
            temp_array = NULL;
            exit(1);
        }
        else {
            temp_array[i] = NULL;
        }
    }

    temp_struct->array = temp_array;
    temp_struct->length = 0;
    temp_struct->max_length = initial_length;

    return temp_struct;

}

Array * deallocate_tab(Array * vector)
{
    if (vector) {
        void** tab = vector->array;
        if (tab)
        {
            int M = _msize(tab) / sizeof(void *);  //ilosc wierszy w macierzy str
            for (int i = 0; i < M; ++i)
            {
                if (tab[i])
                {
                    free(tab[i]);
                    tab[i] = NULL;
                }
            }

            free(tab);
            tab = NULL;
        }
        free(vector);
        vector = NULL;
    }
    return vector;
}

释放循环的第一次迭代顺利进行,在调试器中我可以读取我的值,但在释放数组中的第一项后,其他所有项似乎都不存在,我可以查找它们。

为什么会这样?

【问题讨论】:

  • 为什么这被标记为两种不同的语言?选一个!
  • 对于这些类型的问题,Valgrind 是您的朋友。
  • @Olaf 并不是说​​它们的问题基本相同。不像 C++ 向后兼容...
  • 那么,你不认为Array 的定义可能是相关的吗?
  • int M = _msize(tab) / sizeof(void *); --> int M = vector-&gt;length;

标签: c arrays memory-management


【解决方案1】:

在 c 中,无法仅通过查看数组来确定数组的大小。即这行不通

int M = _msize(tab) / sizeof(void *);

您需要传递大小以及指向其基数的指针

【讨论】:

  • 使用 valgrind(如其他人所说)
  • valgrind 是否可以在 Windows 上运行
猜你喜欢
  • 2017-09-05
  • 2020-12-18
  • 2016-09-07
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多