Linux c程序中函数strcpy的奇怪分段错误

Red*_*and 0 c linux gdb

这是我的源代码:

char *
cpy_strcpy (dest, src)
     char *dest;
     const char *src;
{
  char c;
  char *s = (char *) src;
  const ptrdiff_t off = dest - s - 1;

  do
    {
       //c = *s++
       //s[off] = c;
       s[off] = *s;
    }
  while (*s++ != '\0');
  //while( c != '\0' );
  return dest;
}
Run Code Online (Sandbox Code Playgroud)

当我使用gdb调试它时,我得到了这个:

(gdb) s
26    while (*s++ != '\0');
(gdb) 
27    return dest;
(gdb) 
28  }
(gdb) 

Program received signal SIGSEGV, Segmentation fault.
0x000000000040050a in cpy_strcpy (dest=can't compute CFA for this frame
) at strcpy.c:28
28  }
Run Code Online (Sandbox Code Playgroud)

这个源代码是从glibc复制但我更改了一些行(带注释//)

我真的无法弄清楚我的新代码有什么问题.有人可以帮帮我吗?

提前致谢!

小智 5

s[off] = *s 在第一个循环中是错误的.

s[off]指出地址s + off,在第一个循环中是:

s + off = s + (dest - s - 1) = dest - 1
Run Code Online (Sandbox Code Playgroud)

地址(dest - 1)超出了char数组的左边界.

原始代码是正确的,因为c = *s++首先可以与S指定C,再增加s,这使得s[off]s[off] = c刚指出dest,没有dest - 1.