我有这样简单的程序,它将一个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;
}
释放循环的第一次迭代顺利进行,并在Debuger我可以读我的价值,但释放数组中的第一个项目后,每其他项目似乎是不存在的,我可以查找。 。
这是为什么发生?
为什么这个标记为两种不同的语言?选一个! – Olaf
对于这些类型的问题,[Valgrind](http://valgrind.org)是你的朋友。 – dbush
@Olaf不是说这两个问题基本相同..不像C++是向后兼容... – Haito