我正在学习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: %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 :(得分: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);