I have a pointer array named ipN_details which has type ip_details:
typedef struct
{
char name[64];
char ip[16];
char Flags;
char mac[17] ;
} ip_details;
after calling function get_ip_details when I print elements of ipN_details it contains wrong value for element of mac whenever this array contains more than one member. (all other elements have right values that is expected.) For example, when this array has two member value of mac in the first member is concatenated with some of the last characters of name of second member.
first member: name=mina ip=9.9.9.9 Flags=a mac=3f:fd:df:fdakh
second member: name=simakh ip=9.9.9.1 Flags=ab mac=3f:gv:hj:fd
I have tried to debug this code using gdbafter memcpy line ,
I printed elemnt of mac and it contains right value,I have no idea why it contains wrong value when I print it using cout (I call cout after calling this function get_ip_details). I also printed contents of ipN_details array after memcpy line using gdb. They were also right, thus I think this problem does not relate to function extract_ip.
int get_ip_details(ip_details **ipN_details, int *ip_details_len)
{
int_details *int_details_list=0;
int int_details_list_len = 0;
int ret =
get_int_details(&int_details_list,&int_details_list_len,"eth");
if(ret == 0)
{
int k = 0;
for(int i=0; i < int_details_list_len; i++)
{
ip_details * ipN_details=0;
int ipN_details_len=0;
int int_index = int_details_list[i].index;
extract_ip(int_index,
&ipN_details,&ipN_details_len); // here I read ipN_details_len number of members into ipN_details array using this function
/*
* I wanna add members one by one to array ip_details(using for loop with j),
* thus I increase allocated
* memory of this array using realloc function and then memcpy the members from
* ipN_details function to ip_details, one by one
*/
if (ipN_details_len != 0)
{
*ip_details_len += ipN_details_len;
*ip_details = (ip_details *)realloc(*ip_details,
(*ip_details_len) * sizeof(ip_details));
for(int j=0; j < ipN_details_len; j++)
{
memcpy(&((*ip_details)[k]), &
(ipN_details[j]),sizeof(ip_details));
k++;
}
}
free(ipN_details);
}
free(int_details_list);
}
}
I call this function like this:
ip_details* ips_details=0;
int ips_details_len;
get_ip_details(&ips_details, &ips_details_len);
for(int i=0; i < ips_details_len; i++){
cout << string(ips_details[i].name) << "-"<<
string(ips_details[i].ip_address) << "-" <<
string(ips_details[i].mac_address) << "-" <<
ips_details[i].Flags << endl;
}