[英]Freeing void pointer array, crashes after freeing first element
我有一個簡單的程序,可以將void*
數組包裝到具有長度和自動調整大小的結構中。 雖然在我釋放第一個元素后崩潰了。
#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中,我可以讀取我的值,但是釋放數組中的第一個項目后,其他所有項目似乎都不存在,可以查找它們。
為什么會這樣呢?
在c語言中,無法僅通過查看數組來確定其大小。 即這將不起作用
int M = _msize(tab) / sizeof(void *);
您需要傳遞大小以及指向其基數的指針
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.