2012-01-07 76 views
4

我正在嘗試執行下面的代碼,但是對於每次嘗試都產生了分段錯誤。問題似乎來自標記化中使用的strncpy函數。我對編程有點新鮮感。請幫我調試代碼。請幫助:複製字符串時出現分段錯誤

 /* 
     ** 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]); 
} 
+1

什麼是'返回0; 9'該怎麼辦? – 2012-01-07 12:01:54

回答

6
char* ipStr[9]; 

上面創建9個字符串(指針char)的陣列。但是,它不會爲九個字符串分配內存。

當您將strncpy轉換爲ipStr時,您的程序出現段錯誤。

解決方案:分配內存(例如使用malloc()strdup())。

1

如果地址有效,您的validchk()函數將無法返回TRUE。這將使其行爲或多或少隨機。

你應該重寫它,保持相同的核心驗證規則,如:

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