刪除部我有兩個例子的功能,用於刪除一個數組從陣列
第一個使用的memmove的區段,將這種方法造成的問題,當涉及到釋放分配給輸入陣列的存儲器(輸入數組總是malloc'd,例如它在堆上)?
在調用此函數之前,雙精度輸入數組已被malloc調用。這個函數試圖刪除數組中的值,例如使標準數組看起來有點像動態數組。但是,memmove調用是否意味着當輸入數組隨後被釋放(在此函數返回之後,此函數之外),那麼由於數組已被修改的事實,釋放調用可能無法正常工作?
/**
* Remove a contiguous section of data from an array of doubles
*/
void dbl_array_del(double *array, size_t *plen_array, size_t idx, size_t n_elems)
{
size_t len_array = *plen_array;
/* must delete at least one value */
assert(n_elems > 0);
/* section to remove does not exceed the length of the array */
assert(idx+n_elems <= len_array);
/* function cannot create an 'empty' array */
assert(len_array-n_elems > 0);
if ((idx+n_elems) == len_array) {
/* case where section to be removed reaches end of array, no memory has
* to be shifted, only array length altered */
len_array-=n_elems;
} else {
/* otherwise data to right of section has to be shifted left, back over
* removed section */
memmove(array+idx, array+idx+n_elems,
(len_array-idx-n_elems)*sizeof(double));
len_array-=n_elems;
}
*plen_array = len_array;
}
第二種方法不使用memmove,而是迭代需要左移的值。在內存泄漏方面這是一種更安全的方法嗎?
/**
* Remove a contiguous section of data from an array of doubles
*/
void dbl_array_del(double *array, size_t *plen_array, size_t idx, size_t n_elems)
{
size_t len_array = *plen_array;
/* must delete at least one value */
assert(n_elems > 0);
/* section to remove does not exceed the length of the array */
assert(idx+n_elems <= len_array);
/* function cannot create an 'empty' array */
assert(len_array-n_elems > 0);
/* n is the no. of values that need shifting left */
size_t n = len_array-(idx+n_elems);
size_t i;
/* shift values left */
for (i=idx; i<idx+n; i++) {
array[i] = array[i+n_elems];
}
/* reset values off end of array */
for (i=idx+n; i<len_array; i++) {
array[i] = 0;
}
*plen_array = len_array-n_elems;
}
不確定內存泄漏是您的主要問題。 – concept3d
因爲這兩個版本本身都沒有分配內存,所以內存泄漏根本不會出現。目前還不清楚你認爲會出現什麼樣的問題。 – Jon