C奇怪的数组行为

Luk*_*keN 6 c arrays memset memcpy

得知两后strncmp是不是它似乎并strlcpy没有被使用我的操作系统(Linux)的,我想我可以尝试,并将其写入自己.

我发现了libc维护者Ulrich Drepper的一句话,他发布了另一种strlcpy使用方法mempcpy.我也没有mempcpy,但它的行为很容易复制.首先,这是我的测试用例

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

#define BSIZE 10

void insp(const char* s, int n)
{
   int i;

   for (i = 0; i < n; i++)
      printf("%c  ", s[i]);

   printf("\n");

   for (i = 0; i < n; i++)
      printf("%02X ", s[i]);

   printf("\n");

   return;
}

int copy_string(char *dest, const char *src, int n)
{
   int r = strlen(memcpy(dest, src, n-1));
   dest[r] = 0;

   return r;
}

int main()
{
   char b[BSIZE];
   memset(b, 0, BSIZE);

   printf("Buffer size is %d", BSIZE);

   insp(b, BSIZE);

   printf("\nFirst copy:\n");
   copy_string(b, "First", BSIZE);
   insp(b, BSIZE);
   printf("b = '%s'\n", b);

   printf("\nSecond copy:\n");
   copy_string(b, "Second", BSIZE);
   insp(b, BSIZE);

   printf("b = '%s'\n", b);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这就是结果:

Buffer size is 10                    
00 00 00 00 00 00 00 00 00 00 

First copy:
F  i  r  s  t     b     =    
46 69 72 73 74 00 62 20 3D 00 
b = 'First'

Second copy:
S  e  c  o  n  d          
53 65 63 6F 6E 64 00 00 01 00 
b = 'Second'
Run Code Online (Sandbox Code Playgroud)

您可以在内部表示(insp()创建的行)中看到混合了一些噪声,例如printf()第一个副本之后的检查中的格式字符串,以及第二个副本中的外部0x01.

字符串被完整复制并正确处理太长的源字符串(让我们忽略将0作为长度传递到copy_string现在的可能问题,我稍后会修复它).

但是为什么我的目的地里面有外来数组内容(来自格式字符串)?这就好像目的地实际上是RESIZED以匹配新的长度.

Mar*_*ett 4

字符串的末尾用 \0 标记,之后的内存可以是任何内容,除非您的操作系统故意将其清空,否则它只是留在那里的任何随机垃圾。

请注意,在这种情况下,“问题”不在 copy_string 中,您正好复制​​了 10 个字符 - 但主代码中“first”之后的内存只是随机的。