【发布时间】: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->length;
标签: c arrays memory-management