Reputation: 225
I am trying to execute the below code, but for every attempt I am geting a segmentation fault. The problem seems to be coming from the strncpy function used in tokenizing. I a bit new to programming. Please help me debug the code. Please help:
/*
** Program to accept a binary IP address from the command line and
** if it is a valid IP address, show the user its dotted decimal form.
** Also tell the user, which class of IP address it belongs to
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
int validchk(char uarg[]);
int tokenize(char uarg[], char* uargv[]);
int toNum(char harr[], char iparr[]);
void shownum(char *iparr[]);
void classify(char uarg[]);
void usage();
void mystrncpy(char* arr, char* brr);
int main(int argc, char *argv[])
{
char* ipStr[9];
if (argc != 2) {
usage();
exit(1);
}
if (validchk(argv[1]) == FALSE) {
fprintf(stderr,"Error in the length of the IP Bit Address\n");
exit(1);
}
classify(argv[1]);
if (tokenize(argv[1],ipStr) == -1) {
perror("Error in tokenizing the binary IP address\n");
}
//shownum(ipStr);
return 0;
}
void usage()
{
fprintf(stderr,"Usage: bi2ip <32bitip>\n");
return;
}
int validchk(char uarg[])
{
if (strlen(uarg) != 32) {
return FALSE;
}
}
void classify(char uarg[])
{
int ipcnt = 0;
char *p;
int doneflag = FALSE;
while(ipcnt <= 4) {
p = &uarg[ipcnt];
if (*p == '0') {
doneflag = TRUE;
break;
}
ipcnt++;
}
if (doneflag == FALSE) {
fprintf(stderr,"Failed to classify\n");
exit(1);
}
printf("%c\n",('A'+ipcnt));
return;
}
int tokenize(char uarg[], char* uargv[])
{
int i =0,j;
// for (i = 0; i <4; i++) {
// strncpy(&uargv[i][0],&uarg[j],8);
//strncpy(uargv[1],&uarg[8],8);
//strncpy(uargv[2],&uarg[16],8);
//strncpy(uargv[3],&uarg[24],8);
// uargv[i][8] = '\0';
// j+=8;
for ( j = 0; j<8; j++) {
uargv[0][j] = uarg[j];
uargv[1][j] = uarg[j+8];
uargv[2][j] = uarg[j+16];
uargv[3][j] = uarg[j+24];
}
// }
return 0;9
}
void shownum(char *iparr[])
{
int i,j;
unsigned long arr[4];
for(i = 0; i<4; i++) {
arr[i] = strtoul(iparr[i],NULL,2);
}
for ( j = 0; j < 3; j++) {
printf("%lu.",arr[j]);
}
printf("%lu",arr[3]);
}
Upvotes: 4
Views: 174
Reputation: 399843
Your validchk()
function fails to return TRUE if the address validates. This will make it behave more or less randomly.
You should rewrite it, keeping the same core validation rule, as:
int validchk(const char *string)
{
return (string != NULL) && (strlen(string) == 32);
}
Upvotes: 1
Reputation: 500367
char* ipStr[9];
The above creates an array of 9 strings (pointers to char
). It does not, however, allocate memory for the nine strings.
When you strncpy
into ipStr
, your program segfaults.
Solution: allocate memory (e.g. using malloc()
or strdup()
).
Upvotes: 6