malloc realloc free @ Linux C (invalid address: 0x1010000)

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?)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值