C-超过24个字符后,strncat或strndmp添加了随机字符



我目前正在学习C,我决定制作一个简单的功能,可以交换字符串的两半。我使用strndmp获得了一半的字符串,并使用strncat将另一半添加到strndmp结果的末端。之后,我打印了输出。该脚本换了一半,输出了字符串,但最后几个字符被随机字符替换。我真的很困惑,因为如果我在打印交换字符串或输入的字符串不到24个字符之前,这不会发生这种情况。这是代码:

#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: %dn",strlen(sample));
    printf("Buffer output: %sn",buff);
}
int main() {
    //printf("Uncommenting this will remove the errornn");
    //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

预先感谢。

呼叫strndup只能分配足够的内存在字符串的后半部分,因此,当您向其strncat时,它超出了为buff分配的空间,并且行为不确定。您可能希望我们沿着这些台词:

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