Reputation: 883
I have to write a program for my C programming class that converts IPV4 addresses into IPV6. We were supplied with the function to do the conversion (the below code does the actual converting). I am having problems in XCode when ever I run this code. I have used break points and worked out that it is crashing when it hits the sprintf()
line. It crashes with: Program received signal: “SIGABRT”.
sharedlibrary apply-load-rules all
. I have tested the exact same code on a Windows based compiler and it runs fine. What would cause it to fail on one and not the other? My program hast to run on Windows, not Mac for the grading process of if there is no fix for this then I will make do and write the rest of the program on Windows but I would prefer to use Mac so any help is appreciated.
strncpy(IPV6, "0000:0000:0000:0000:0000:0000:", 30);
sscanf(input, "%u.%u.%u.%u", &a, &b, &c, &d);
sprintf(hexIP, "%02X%02X:%02X%02X", a, b, c, d );
strncat(IPV6, hexIP, 9);
Thanks
EDIT
int makeIPV6(const char input[25], char IPV6[40], int style)
{
unsigned int a, b, c, d, e, f;
char hexIP[9];
char hexMAC[24];
printf("Stage 2\n");
strncpy(IPV6, "0000:0000:0000:0000:0000:0000:", 30);
sscanf(input, "%u.%u.%u.%u", &a, &b, &c, &d);
sprintf(hexIP, "%02X%02X:%02X%02X", a, b, c, d );
strncat(IPV6, hexIP, 9);
return strlen(IPV6)
}
Upvotes: 1
Views: 1129
Reputation: 434915
I see a buffer overflow:
char hexIP[9];
/*...*/
sprintf(hexIP, "%02X%02X:%02X%02X", a, b, c, d );
Your format string will yield 9 characters but sprintf
will include the nul terminator. Try making hexIP
ten characters.
And pay attention to what Joey Adams said or memset(IPV6, '\0', 40)
before you try to put anything in it.
Upvotes: 6
Reputation: 43400
You have fallen fowl of strncpy
's annoying caveat, namely that if a null terminator is not among the first n bytes of the source string, no terminator will be appended to the output buffer.
char buffer[999];
strcpy(buffer, "xxxxxxxxxx");
strncpy(buffer, "12345", 5);
puts(buffer);
This prints 12345xxxxx
rather than 12345
.
When you see strncpy
, warning bells should go off in your head. In this case, you're better off just saying:
strcpy(IPV6, "0000:0000:0000:0000:0000:0000:");
With your current code, a null terminator may or may not appear at the end of the IPV6 string.
Upvotes: 4