Segmentation error while copying a row

I am trying to execute the code below, but for each attempt I get a segmentation error. The problem seems to be related to the strncpy function used in tokenization. I am a little 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]); } 
+4
source share
2 answers
 char* ipStr[9]; 

The above array contains 9 lines (pointers to char ). However, it does not allocate memory for nine lines.

When you strncpy in ipStr , your program is segfaults.

Solution: allocate memory (for example, using malloc() or strdup() ).

+6
source

The validchk() function does not return TRUE if the address is verified. This will make him behave more or less randomly.

You should rewrite it, keeping the same rule of checking the kernel, as:

 int validchk(const char *string) { return (string != NULL) && (strlen(string) == 32); } 
+1
source

Source: https://habr.com/ru/post/1389793/


All Articles