2017-04-13 81 views
0

我有這樣簡單的程序,它將一個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我可以讀我的價值,但釋放數組中的第一個項目後,每其他項目似乎是不存在的,我可以查找。 。

這是爲什麼發生?

+0

爲什麼這個標記爲兩種不同的語言?選一個! – Olaf

+3

對於這些類型的問題,[Valgrind](http://valgrind.org)是你的朋友。 – dbush

+0

@Olaf不是說這兩個問題基本相同..不像C++是向後兼容... – Haito

回答

0

在c中,無法簡單地通過查看來確定數組的大小。即這是不行的

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

您需要通過周圍的大小以及一個指向它的基礎

+0

陣列的大小不是一個問題,我相信.. – Haito

+0

使用valgrind(如別人說) – pm100

+0

Valgrind在Windows上運行雖然 – Haito