I am writing a function which takes in the integer value and the pointer to a character. the function converts the integer value into binary and stores it in the char pointer. the char pointer is 16 bytes long.
Snippet of code:
void int2bin(u_int16_t addr_IP, char *Binary)
{
int count;
printf("IP1add = %d \n", Binary);
for (count = 0; count < 16; count++) {
if(addr_IP>0)
*(Binary + 15-count) = addr_IP & 开发者_运维知识库0x1 ? '1':'0';
else
*(Binary + 15-count) = '0';
addr_IP>>=1;
}
}
int main(int argc, char *argv[])
{
u_int16_t senderIP_16[], u_int16_t receiverIP_16[];
char sender_IP_hi[16], sender_IP_low[16];
int2bin(senderIP_16[0], &sender_IP_hi);
int2bin(senderIP_16[1], &sender_IP_low);
}
In the first call to the function, it returns correct values. But in the second pass, the value of first pass is appended to the second pass, i.e length of sender_IP_low
becomes 32.
How can I resolve this?
Thanks
It looks like you're printing sender_IP_low
as a string, and since it is not null-terminated, the print routine continues to print the adjacent buffer, sender_IP_hi
. And you're probably just lucky that the print routine finds a zero and stops before a segmentation fault.
One quick fix is:
void int2bin(u_int16_t addr_IP, char *Binary) {
...
Binary[16] = 0; // terminate the string before returning
}
...
char sender_IP_hi[17], sender_IP_low[17]; // +1 for null terminator
Although, there are a few other things that could be fixed in your implementation, I just wanted to focus on an answer to your original question.
If you are printing the arrays with printf():
void int2bin(u_int16_t addr_IP, char *Binary)
{
int count;
printf("IP1add = %d \n", Binary);
for (count = 0; count < 16; count++) {
if(addr_IP>0)
*(Binary + 15-count) = addr_IP & 0x1 ? '1':'0';
else
*(Binary + 15-count) = '0';
addr_IP>>=1;
}
// Put the NULL char in the last position
Binary[16] = '\0';
}
int main(int argc, char *argv[])
{
u_int16_t senderIP_16[], u_int16_t receiverIP_16[];
// One more char for storing the terminator character
char sender_IP_hi[17], sender_IP_low[17];
int2bin(senderIP_16[0], &sender_IP_hi);
int2bin(senderIP_16[1], &sender_IP_low);
}
精彩评论