2017-09-27 25 views
-1

我目前正在學習C,我決定做一個簡單的函數來交換字符串的兩半。我使用strndmp來獲取字符串的一半,並使用strncat將另一半添加到strndmp結果的末尾。之後,我打印輸出。該腳本輸出了字符串,其中兩半交換了,但最後幾個字符被隨機字符替換。我真的很困惑,因爲如果我在打印交換字符串之前打印某些內容或輸入的字符串未滿24個字符,則不會發生這種情況。下面的代碼:超過24個字符後strncat或strndmp添加隨機字符

#include <stdio.h> 
#include <string.h> 

void halfSwap(char * sample); 
void halfSwap(char * sample){ 
    char * buff; 
    buff = strndup(sample+strlen(sample)/2,strlen(sample)); 
    strncat(buff,sample,strlen(sample)/2); 
    printf("Sample length: %d\n",strlen(sample)); 
    printf("Buffer output: %s\n",buff); 
} 
int main() { 
    //printf("Uncommenting this will remove the error\n\n"); 
    //Characters only go missing after sample exceeds 24 chars 
    halfSwap(" worrrrrrrlddhellllllllooo"); 
    //Error does not occur after printng once 
    halfSwap(" worrrrrrrlddhellllllllooo"); 
} 

,輸出是:

Sample length: 26 
Buffer output: hellllllllooo worrrrrrrl 
Sample length: 26 
Buffer output: hellllllllooo worrrrrrrldd 

在此先感謝。

+0

你在'halfSwap()'每次你調用它泄漏內存。 –

+1

AFAICS,['strndup()']的規範(http://pubs.opengroup.org/onlinepubs/9699919799/functions/strndup.html)並不保證分配與第二個參數一樣多的內存。如果輸入比第二個參數短,它只能爲輸入分配足夠的空間,包括空終止符。因此,追加到分配的空間是未定義的行爲。如果您在可以運行[Valgrind](http://valgrind.org/)的平臺上,請使用它。 –

+0

如果您通過調試代碼(例如,通過* code-blocks *)來幫助自己,您可能會自己得到答案。此外,調試和檢查變量和指針的值將幫助您更快地學習。 – ssd

回答

0

對strndup的調用只爲字符串的後半部分分配足夠的內存,所以當你對它進行strncat時,它超出了爲buff分配的空間,並且行爲是未定義的。你可能想要的,而不是我們沿着這些線:

int len = strlen(sample); 
int half = len/2; 
buff = (char*)malloc(len+1); 
strcpy(buff,&sample[half]); 
strncat(buff,sample,half);