@@ -60,12 +60,18 @@ static bool_t darray_extend(darray_t* darray) {
60
60
return TRUE;
61
61
} else {
62
62
void * elms = NULL ;
63
+ uint32_t old_capacity = darray -> capacity ;
63
64
uint32_t capacity = (darray -> capacity >> 1 ) + darray -> capacity + 1 ;
64
65
65
66
elms = TKMEM_REALLOCT (void * , darray -> elms , capacity );
66
67
if (elms ) {
67
68
darray -> elms = elms ;
68
69
darray -> capacity = capacity ;
70
+
71
+ /* 将新分配的内存区域初始化为NULL */
72
+ if (capacity > old_capacity ) {
73
+ memset (darray -> elms + old_capacity , 0 , (capacity - old_capacity ) * sizeof (void * ));
74
+ }
69
75
70
76
return TRUE;
71
77
} else {
@@ -124,21 +130,26 @@ ret_t darray_remove_range(darray_t* darray, uint32_t start, uint32_t end) {
124
130
return_value_if_fail (darray != NULL && start < end && end <= darray -> size , RET_BAD_PARAMS );
125
131
126
132
if (darray -> elms != NULL ) {
127
- uint32_t i = 0 , j = 0 ;
133
+ uint32_t i = 0 ;
134
+ uint32_t range_size = end - start ;
128
135
void * * elms = darray -> elms ;
129
136
130
- for (i = start , j = end ; i < darray -> size ; i ++ , j ++ ) {
131
- if (i < end ) {
132
- void * iter = elms [i ];
133
- darray -> destroy (iter );
134
- }
135
- if (j < darray -> size ) {
136
- elms [i ] = elms [j ];
137
- } else {
138
- elms [i ] = NULL ;
139
- }
137
+ /* 首先销毁要删除范围内的元素 */
138
+ for (i = start ; i < end ; i ++ ) {
139
+ darray -> destroy (elms [i ]);
140
+ }
141
+
142
+ /* 将end之后的元素向前移动 */
143
+ for (i = start ; i + range_size < darray -> size ; i ++ ) {
144
+ elms [i ] = elms [i + range_size ];
140
145
}
141
- darray -> size -= (end - start );
146
+
147
+ /* 清空尾部的元素指针 */
148
+ for (i = darray -> size - range_size ; i < darray -> size ; i ++ ) {
149
+ elms [i ] = NULL ;
150
+ }
151
+
152
+ darray -> size -= range_size ;
142
153
}
143
154
144
155
return RET_OK ;
@@ -284,12 +295,15 @@ ret_t darray_sorted_insert(darray_t* darray, void* data, tk_compare_t cmp,
284
295
if (index >= 0 ) {
285
296
if (replace_if_exist ) {
286
297
return darray_replace (darray , index , data );
298
+ } else {
299
+ /* 元素已存在但不替换,插入到找到位置之后 */
300
+ index ++ ;
287
301
}
288
302
} else {
289
303
index = low ;
290
304
}
291
305
292
- if (index >= darray -> size ) {
306
+ if (index >= ( int32_t ) darray -> size ) {
293
307
return darray_push (darray , data );
294
308
} else {
295
309
return darray_insert (darray , index , data );
@@ -422,6 +436,9 @@ int32_t darray_bsearch_index_ex(darray_t* darray, tk_compare_t cmp, void* ctx, i
422
436
return_value_if_fail (darray != NULL , -1 );
423
437
424
438
if (darray -> size == 0 ) {
439
+ if (ret_low != NULL ) {
440
+ * ret_low = 0 ;
441
+ }
425
442
return -1 ;
426
443
}
427
444
if (cmp == NULL ) {
0 commit comments