Question about memory allocation when initializing char arrays in C/C++.
- by Carlos Nunez
Before anything, I apologize if this question has been asked before.
I am programming a simple packet sniffer for a class project. For a little while, I ran into the issue where the source and destination of a packet appeared to be the same. For example, the source and destination of an Ethernet frame would be the same MAC address all of the time. I custom-made ether_ntoa(char *) because Windows does not seem to have ethernet.h like Linux does. Code snippet is below:
char *ether_ntoa(u_char etheraddr[ETHER_ADDR_LEN])
{
int i, j;
char eout[32];
for(i = 0, j = 0; i < 5; i++)
{
eout[j++] = etheraddr[i] >> 4;
eout[j++] = etheraddr[i] & 0xF;
eout[j++] = ':';
}
eout[j++] = etheraddr[i] >> 4;
eout[j++] = etheraddr[i] & 0xF;
eout[j++] = '\0';
for(i = 0; i < 17; i++)
{
if(eout[i] < 10)
eout[i] += 0x30;
else if(eout[i] < 16)
eout[i] += 0x57;
}
return(eout);
}
I solved the problem by using malloc() to have the compiler assign memory (i.e. instead of char eout[32], I used char * eout; eout = (char *) malloc (32);). However, I thought that the compiler assigned different memory locations when one sized a char-array at compile time. Is this incorrect?
Thanks!
Carlos Nunez