static int add_single_element_to_array (msg_count_type ** source_array,
int * arr_count_ptr
int * arr_reserved_cnt_ptr
msg_count_type * need_added_element)
{
int status = 0;
int i = 0;
msg_count_type * new_ptr = NULL;
/* Return if the id exsits in the array */
for ( i = 0; i < * arr_count_ptr; i ++, source_array ++ )
{
if (strcmp(need_added_element->id, source_array->id) == 0)
{
return -1;
}
}
/* If get here, add the element to the array */
new_ptr = (*msg_count_type)
block_realloc ((void **) source_array,
arr_count_ptr,
arr_reserved_cnt_ptr,
BLOCK_SIZE,
sizeof (msg_count_type));
strcpy (new_ptr -> id,
need_added_element -> id,
sizeof (new_ptr -> id) - 1);
/* Return */
return status;
}
static void process (Bool is_orign)
{
message_count_type *source_array;
int message_count;
int reserved_cnt;
message_count_type *msg_item;
for (...)
{
add_single_element_to_array (&source_array,
&message_count,
&reserved_cnt,
msg_item);
}
/* Make sure release memory */
free (source_array); /* Runtime error like - invalid address: 0x1010000.... */
}
问题出在 source_array ++ ,经过第一次调用add_single_element_to_array,source_array 已经不再指向首地址,而是尾地址;当调用free释放内存时- 无效地址。使用下标方式取值就好使, source_array[i]->id .
(还没搞明白为什么非要指向首地址才能free?)