简体   繁体   English

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

[英]Strange Segmentation fault of function strcpy in linux c program

Here is my source code: 这是我的源代码:

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;
}

I got this when i using gdb debug it: 我在使用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  }

This source code was copied from glibc but i changed some line(with comment //) 此源代码是从glibc复制而来,但我更改了一些行(带有注释//)

I really can't figure out what is wrong with my new code. 我真的不知道新代码出了什么问题。 anyone can help me? 有人可以帮助我吗?

Thanks in advance! 提前致谢!

s[off] = *s is wrong in the first loop. s[off] = *s在第一个循环中是错误的。

s[off] points the address s + off , which in the first loop is: s[off]指向地址s + off ,在第一个循环中为:

s + off = s + (dest - s - 1) = dest - 1

The address (dest - 1) is out of the left bound of char array. 地址(dest - 1)超出char数组的左边界。

The original code is right, because c = *s++ can firstly assign c with s, then increase s, which makes s[off] in s[off] = c just points to dest , not dest - 1 . 原码是正确的,因为c = *s++可以首先分配c。与s,则增加s,这使得s[off]s[off] = c只是指向dest ,不dest - 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM