2014-08-27 42 views
0

您好,我有這樣的代碼(在這裏發現,在計算器)段錯誤微調空間C時

char *trim_whitespace(char *string) 
    { 
    char *str; 
    str = (char *) malloc(strlen(string) + 1); 
    memcpy(str, string, strlen(string)); 
    printf("%d\n", strlen(str)); 
    char *end; 

    if (str == NULL) { 
     return NULL; 
    } 
    // Trim leading space 
    while(isspace(*str)) str++; 

    if(*str == '\0') // All spaces? 
     return str; 

    // Trim trailing space 
    end = str + strlen(str) - 1; 
    while(end > str && isspace(*end)) end--; 

    // Write new null terminator 
    *(end+1) = '\0'; 

    return str; 

} 

,並在主

int main(int argc, char **argv){ 


    char *t; 
    t = trim_whitespace(argv[1]);; 
    printf(";%s;\n",t); 
    free(t); 
} 

,但現在它失敗

*** Error in `./a.out': free(): invalid pointer: 0x00000000020dd014 *** 
Aborted (core dumped) 

如果我跑

trim_whitespace(argv[1]); 

everythink去好了,我有結果,我想,它返回修剪字符串,但如果我運行這樣的代碼

trim_whitespace("abc"); 

它會失敗,上線段錯誤與

*(end+1) = '\0'; 

請幫助我與我的問題。謝謝。 P.S.這個函數從很多地方調用,是否可以改變trim_whitespace內的水平?

+0

這是一個全新的問題現在更好的問一個新的問題引用這一個(順便說一句:這是因爲trim_whitespace()並不一定返回分配的指針) – 2014-08-27 11:24:13

回答

0

trim_whitespace("abc");會嘗試修改一個常量數據。

​​是一個常量,可以分配在恆定的空間(即:保留爲只讀訪問的內存中的位置)。