2016-01-21 59 views
-1

我有一個字符串數組,我試圖爲這些字符串之一malloc更多的空間,所以我可以更改值的字符串。當我爲一個字符串數組中的字符串malloc更多的空間時,字符串數組重複了一些字符串

int catenate_strings (char** arr, int index1, int index2) { 
    char *new_string; 
    new_string = malloc(1000*sizeof(char)); 
    if (new_string == NULL) { 
     printf("\nError allocating memory\n"); 
    } 

    strcpy(new_string, arr[index1]); 
    strcat(new_string, arr[index2]); 
    arr[index1] = new_string; 
} 

然而,當我跑我的代碼,它會爲某些情況下工作,但在別人將重複串在索引1,並把它放在索引1 + 1爲好。

+0

你想「調整」一個字符串? –

+2

請發佈[MCVE](http://stackoverflow.com/help/mcve)。 –

+1

當您執行'arr [index1] = new_string'時,內存泄漏,您正在丟失前一個字符串。 –

回答

1

你的代碼有一些問題:在arr[index1] = new_string

  1. 內存泄漏,因爲你沒有釋放舊緩衝區。
  2. 如果結果字符串長於1000字節,則會發生緩衝區溢出。
  3. 儘管函數具有返回值int,但不會從catenate_strings返回任何值。

如果arr所有條目都使用malloc分配的,那麼你可以使用realloc

int catenate_strings (char** arr, int index1, int index2) 
{ 
    // Resize buffer to hold old string + new string (+ terminating null byte!) 
    char * const new_string = realloc(strlen(arr[index1]) + strlen(arr[index2]) + 1); 
    if (new_string == NULL) { 
     printf("\nError allocating Memory, cannot resize string\n"); 
     return -1; 
    } 
    strcat(new_string, arr[index2]); 
    arr[index1] = new_string; 

    return 0; 
} 

的複製到index+1來自所示的代碼,而是出自於你的代碼別的地方。

相關問題