我是C新手,在C決定釋放一個對象時以及它決定保留一個對象時並沒有真正掌握它。如何防止c中的懸掛指針/垃圾?
heap_t是指向結構堆的指針。
heap_t create_heap(){
heap_t h_t = (heap_t)malloc(sizeof(heap));
h_t->it = 0;
h_t->len = 10;
h_t->arr = (token_t)calloc(10, sizeof(token));
//call below a couple of times to fill up arr
app_heap(h_t, ENUM, "enum", 1);
return h_t;
}
把h_t通過
int app_heap(heap_t h, enum symbol s, char* word, int line){
int it = h->it;
int len = h->len;
if (it + 1 < len){
token temp;
h->arr[it] = temp;
h->arr[it].sym = s;
h->arr[it].word = word;
h->arr[it].line = line;
h->it = it + 1;
printf(h->arr[it].word);
return 1;
} else {
h->len = len*2;
h->arr = realloc(h->arr, len*2);
return app_heap(h, s, word, line);
}
}
爲什麼我h_t->改編與垃圾填滿,最終我得到一個分段錯誤?我該如何解決?任何C編碼技巧/風格,以避免這樣的東西?
什麼是「標記」?對於它的價值,我不認爲你需要聲明令牌溫度並將其分配給h-> arr [it]。鑑於h-> arr是一個標記指針,並且您有它的內存,h-> arr [it]已經是一個標記結構。 – 2012-01-17 14:25:15
當你說「填滿垃圾」時,你怎麼知道這一點?有什麼症狀? – 2012-01-17 14:27:21