P
Pieter Droogendijk
Just having a bit of trouble programming with C under FreeBSD 5.1 using the
gcc compiler. I'm a bit new to C so my apologies if the answer to my
question appear obvious
Basically I've written a function that will check whether a string is an ip
address (see the function isIP below). During my attempt at debugging this
problem I inserted a printf statement before the return command from the
statement, and also a printf statement after the function's call.
Strangely, the last printf in the function prints, but not the printf after
the function has been called. So somewhere something causes a problem
during the attempt at exiting the function.
FreeBSD prints:
Segmentation fault (core dumped)
which from what I've read basically means that I'm mayhaps addressing memory
outside the current segment. I've got no idea what's wrong, but also more
importantly, I don't know how to go about debugging the problem? So any
insights into debugging segmentation faults (or core dumps) would be
appreciated. I tried using lint but that doesn't really give me any useful
information...or not any information useful to me
Thanks for your time, much appreciated
/*
* checks whether a string is an IP address
* (it basically splits the string, checks that it has 4 segments and that
each segment is a number between 0 and 255)
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int isNumber(char* chars);
char iptemp[3+1+3+1+3+1+3+1]; /* Ip address won't get longer than this */int isIP(const char *ip) {
char* segment;
int segmentcount = 0;
/* You knew about isascii(), but not about isdigit()? */// we mustn't change the IP pointer (strtok changes content)
memcpy(iptemp, ip, strlen(ip)+1 );
segment = strtok(iptemp, ".");
while (segment != NULL) {
// increment our number of segments
segmentcount++;
// check whether the retrieved segment is a digit
if (!isNumber( segment )) {
return 0;
}
// check whether the number is between 0 and 255
if ( atoi(segment) > 255 ) {
return 0;
}
// retrieve the next segment
segment = strtok(NULL, ".");
}
// an IP address consists of 4 segments
if (segmentcount != 4) {
return 0;
}
return 1;
}
The function isNumber is just:
int isNumber(char* chars) {
char* ptr;
int asciicode;
ptr = chars;
while (*ptr != '\0') {
if (!isdigit (*ptr))
return 0;