Ç -

2013-10-22 26 views
0

我已用C寫該功能的功能的內部動力分配/ rellocation(功能應當接收char*,分配必要的空間,並插入字符賦予一個指向字符的索引指針的後面)Ç -

void add_to_str(char *character, char ** string, int* index) 
{ 
    //we dont expect *string to be NULL !! no condition done 
    if (*index == 0) //if str is empty we will alloc AVGLEN(32) characters space 
     *string=malloc(AVGLEN*sizeof(char)); 

    if (*string == NULL) //malloc fails? 
    { 
     fprintf(stderr,errors[MALLOC]); 
     exit(99); 
    } 
    //string length exceeds 32 characters we will allocate more space 
    if (*index > (AVGLEN-1) || character== NULL)// or string buffering ended, we will free redundant space 
    { 
     *string=realloc(*string,sizeof(char)*((*index)+2));//+1 == '\0' & +1 bcs we index from 0 
     if (*string==NULL) //realloc fails? 
     { 
      fprintf(stderr,errors[REALLOC]); 
      exit(99); 
     } 
    } 
    *string[(*index)++]=*character; 
} 

*index > 0,它給我就行了分段錯誤

*string[(*index)++]=*character; 

此功能(的一個變種後面char*只是malloc,然後指定字符string[i++])完美運作。

+0

我建議移動任何'++'等在任何非平凡的表達式內部到他們自己的語句。編譯器在優化之後應該仍然會產生相同的輸出,並且您可能會避免一些意外的行爲並且有更清晰的代碼。 – hyde

回答

3

你必須要小心這樣的說法:

*string[(*index)++]=*character; 

因爲數組索引比指針廢棄更高的優先級。因此,這與

*(string[(*index)++]) = *character; 

這不是你想要的。你想這樣的:

(*string)[(*index)++] = *character; 

的故障代碼,因爲在這種情況下,語句相當於**string,這仍然是有效的工程*index == 0,但是當index > 0string會在一個無效的位置被取消引用:string+index

+0

非常感謝你的先生:) – Smarty77

0

需要注意的是做這樣的事情:

ptr = realloc(ptr, ...); 

是一個非常糟糕的模式。當realloc()失敗時,您的舊分配區域不再可供該程序訪問並泄漏。正確的模式是:

char* str_new = realloc(string, ...); 

if (str_new != NULL) 
    string = str_new; 
else 
    /* handle allocation error */ 
+0

是的,我現在看到,順便說一句,在這個程序當然是真的,我不需要重新分配失敗時的字符串的其餘部分,但至少我可以自由()它仔細,謝謝:) – Smarty77

0

首先,功能fprintf需要一個格式字符串。

I.e.

fprintf(stderr,errors[MALLOC]); 

可能無效。

此功能的目的是什麼。似乎沒有敘述,

+0

btw它的工作原理錯誤*是一個關聯字符串數組的形式(smt像這樣)const char * const errors [] = {MOLOC] =「錯誤:Malloc()的動態內存分配失敗\ n」 } – Smarty77