Pass char pointer to C function
tiktak
I am trying to get the mac address with the following code:
void getMacAdress(unsigned char **address)
{
int s;
struct ifreq buffer;
s = socket(PF_INET, SOCK_DGRAM, 0);
memset(&buffer, 0x00, sizeof(buffer));
strcpy(buffer.ifr_name, "eth0");
ioctl(s, SIOCGIFHWADDR, &buffer);
close(s);
*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
for (s = 0; s < 6; s++)
{
printf("%.2X ", *(*address + s));
}
printf("\n");
}
int main(int argc, char *argv[])
{
unsigned char *address;
getMacAdress(&address);
int i;
for (i = 0; i < 6; i++)
{
printf("%.2X ", *(address + i));
}
printf("\n");
return 0;
}
I got the correct result
08 00 27 0A 4E 98
08 00 27 0A 4E 98
But when I remove the printf
code snippet in the function getMacAddress()
it becomes:
void getMacAdress(unsigned char **address)
{
int s;
struct ifreq buffer;
s = socket(PF_INET, SOCK_DGRAM, 0);
memset(&buffer, 0x00, sizeof(buffer));
strcpy(buffer.ifr_name, "eth0");
ioctl(s, SIOCGIFHWADDR, &buffer);
close(s);
*address = (unsigned char *)buffer.ifr_hwaddr.sa_data;
printf("\n");
}
I get wrong results
08 00 00 00 00 00
Can you explain to me why, and how to fix this problem?
will
You cannot point to stack space to be returned in a function.
Instead, you can allocate a heap space to store the desired result:
void getMacAdress(unsigned char **address)
{
int s;
struct ifreq buffer;
s = socket(PF_INET, SOCK_DGRAM, 0);
memset(&buffer, 0x00, sizeof(buffer));
strcpy(buffer.ifr_name, "eth0");
ioctl(s, SIOCGIFHWADDR, &buffer);
close(s);
*address = (unsigned char*) malloc(sizeof(buffer.ifr_hwaddr.sa_data));
memcpy(*address, buffer.ifr_hwaddr.sa_data,sizeof(buffer.ifr_hwaddr.sa_data));
//for (s = 0; s < 6; s++)
//{
// printf("%.2X ", *(*address + s));
//}
//printf("\n");
}
By the way, don't forget to free the heap space in the main function.