[英]How to free a part of contiguous allocated memory in c?
我是 C 的新手。 我有一個程序,它使用存儲指針的calloc()
分配一些 memory。 這些指針指向 memory 中我存儲人員數據的位置。 每個人一個指針。 所以當我需要刪除數據時,我free()
指向這些數據的指針。 但是帶有指針的 memory 仍然有那個。 我也想解放那個地方。 據我所知,例如,我不能說free(ptr+5)
。 我怎樣才能做到這一點?
您不能釋放已分配塊的開頭或中間,而只留下已分配塊的結尾; 所以(用於刪除數組中的條目):
將您要刪除的條目之后的所有內容移動到已分配塊的末尾向已分配塊的開頭; 這樣要移除的部分就在最后
使用realloc()
減小分配塊的大小(在最后釋放塊)。
狡猾的例子(假設i
是你想要釋放的條目):
memmove(&myArray[i], &myArray[i+1], (total_entries - 1 - i) * sizeof(myArray[0]) );
temp = realloc(myArray, total_entries - 1 * sizeof(myArray[0]));
if(temp == NULL) {
/* Ooops. Need to handle the error somehow */
} else {
myArray = temp;
total_entries--;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.