C中的指针导致未知的随机字符

Nas*_*ium 0 c arrays string pointers char

我有一些C代码打印字符串char数组两次.

Code:

char* twice(char *s) {
   int size=strlen(s),i=0;
   int length=size*2;
   char check = s[size-1];
   char* s2 = malloc(length * sizeof(char));
   char* reset = malloc(size * sizeof(char));
   memcpy(reset, s, size * sizeof(char));

   while (i<length) {
      printf("%s\n", s);
      s2[i] = *s;
      if(s2[i] == check && i == size-1){
        s = reset;
      }else s++;
      i++;
    }
   return s2;
}

int main(){
    char s[] = "hello1234";
    printf("%s\n", twice(s));

    return 0;
}


Output:

hello1234
ello1234
llo1234
lo1234
o1234
1234
234
34
4
hello1234
ello1234
llo1234
lo1234
o1234
1234
234
34
4
hello1234hello1234Ms?
Run Code Online (Sandbox Code Playgroud)

输入的字符串是hello1234,我打印出每个指针,以显示它正确地贯穿字符串两次.但由于某种原因,答案包括Ms?导致hello1234hello1234Ms?为什么会这样?

Jon*_*ood 6

在C中,字符串以带有值的特殊字符终止'\0'.

memcpy()适用于内存,它不是特定于字符串.因此,它不会复制终结符,因为您没有给它包含终止符的长度.(strlen()不包括终结者.)

printf()找不到终结符时,它只是继续打印内存中的任何内容.附加字符只是随机的,在不同的设置上会有所不同.