簡體   English   中英

訪問字符串數組時出現奇怪的分段錯誤

[英]Weird segmentation fault while accessing string array

抱歉直接發布我的項目代碼。 我一直在努力解決這個奇怪的段錯誤,該錯誤發生在for(j = 0; j <100 && * nnames [j]!=(char *)NULL; j ++)行中 以這種方式(* arr [])訪問char **數組不合法嗎?

    char** nnames = getcannames();
    char * new_str ;

    int j =0, len=0;
    ////////////////SEG FAULT HERE //////////////////
    for(j=0; j<100 && *nnames[j] != (char *) NULL; j++){
        len = len + strlen(nnames[j]);

    }
    if((new_str = (char*) malloc(len + 3)) != NULL){
        new_str[0] = '\0';   // ensures the memory is an empty string
        int i=0;    
        //setbuf(client_reply, NULL);
        for(i=0; i<7; i++){ //fix this, garbage values after index 68
            if(*nnames[i] == (char *) NULL) break;

            char *canname = strsave(nnames[i]);


            if( (find_newline = strchr( canname, NEWLINE )) != NULL )
                *find_newline = EOS;
            if(strcmp(canname, "!") != 0){
                strcat(new_str, canname);
                strcat(new_str, "\n");
            }

            //strcat(new_str, "\n\n");  
        }
        strcat(new_str,"\n\0");
        printf("%s", new_str);
        //strcpy( new_str, buf );
        buf = new_str;

    } else {
        perror("malloc failed!\n");
        // exit?
    }


char** getcannames(){
    //INITIALIZE
     char *names[100];
    int i;
    for(i=0; i<100; i++){
        names[i] = strsave("\0");
    }
    int namespos = 0;

     struct sym_list *sp;
     for( sp = Head.s_next;
     sp != (struct sym_list *) NULL;
     sp = sp->s_next )
    {
    if(getcannameindex(names, sp->s_sym.v_value) == -1){
        //strcpy(names[namespos++], sp->s_sym.v_name);
        names[namespos++] = strsave(sp->s_sym.v_value);
    }
    }
    return names;

}

如果nnames是指向char *類型的指針數組的第一個元素的指針,則有效代碼如下所示

for ( j = 0; j < 100 && nnames[j] != NULL; j++ ){
        len = len + strlen(nnames[j]);

假設數組的最后一個元素為空指針。

聲明同樣有效

if(*nnames[i] == (char *) NULL) break;

那就是它必須像

if ( nnames[i] == NULL ) break;

還有這個功能

char** getcannames(){
    //INITIALIZE
     char *names[100];

     //...

     return names;

}

具有未定義的行為,因為它返回指向本地數組第一個元素的指針,該指針在退出函數后將被破壞。

考慮到如果函數strsave動態創建作為參數傳遞給它的字符串的副本

char *canname = strsave(nnames[i]);

則該程序有內存泄漏,因為您沒有釋放canname。

當然,您可能會這樣寫

strcat(new_str,"\n\0");

甚至喜歡

strcat(new_str,"\n\0\0\0\0");

但是兩個語句都等效於

strcat(new_str,"\n");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM