So I'm doing this codewars kata and I'm succeding in every test but in the end the result fails because my code has a segmentation fault and I don't think I know enough about the language to find it! Can someone please halp?
int is_valid_ip(const char *addr)
{
char set[] = "1234567890";
int current;
int octet_counter = 0;
char *octet = 0;
octet = strtok(addr, ".");
while (octet)
{
if (strspn(octet, set) != strlen(octet)) return 0; // checks for spaces
if (strlen(octet) > 1 && (octet[0]) == '0') return 0; // checks for preceding zeros
sscanf(octet, "%d", ¤t);
if (current < 0 || current > 255) return 0; // checks for range
octet = strtok(0, ".");
++octet_counter;
}
if (octet_counter == 4) return 1; // checks for number of octets
return 0;
};
My code was kind of cleaner but after so much messing around trying to solve this problems it's become this...
As strtok() modifies the string to be tokenized and addr is defined as const char * (I assume this is a requirement) you may make a copy of the input string *addr:
char ip[16]; // enought to hold nnn.nnn.nnn.nnn
if(strlen(addr)>15) return 0;
strcpy(ip, addr);
subsequently operate on ip instead of addr
Or... avoid using strtok and parse/scan the string without modifying it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With