【问题标题】:strcpy() and string left shift gives wrong resultstrcpy() 和字符串左移给出错误的结果
【发布时间】:2015-12-19 10:52:32
【问题描述】:

在某些项目中,我有一段 C 代码工作错误,但仅限于特定的输入字符串。我只编译这一段:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define slength 1000    // max string length
char ss[slength];
int main(void) {
    strcpy(ss, "\"abcdefghijkl\"");
    printf("1 %s\n",ss);
    if (ss[0]=='"') {       // remove quotes
        printf("2 %s\n",ss);
        strcpy(ss, ss+1);   // remove first symbol - quote
        printf("3 %s\n",ss);
        ss[strlen(ss)-1]='\0';  //last symbol
        printf("4 %s\n",ss);
    }
    printf("5 %s\n",ss);
    return EXIT_SUCCESS;
}

结果是

1 "abcdefghijkl"
2 "abcdefghijkl"
3 abcdefhhijkl"
4 abcdefhhijkl
5 abcdefhhijkl

所以我得到“abcdefhhijkl”而不是“abcdefghijkl”。我哪里错了?谢谢。

附注我希望我的代码中没有任何多字节/Unicode 字符,但可能需要额外检查。

gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 
Linux test-i3 3.13.0-63-generic #104~precise1-Ubuntu SMP Tue Aug 18 17:03:00 UTC 2015 i686 i686 i386 GNU/Linux

【问题讨论】:

  • strcpy 中的源字符串和目标字符串不能重叠。你可以试试memmove(ss, ss+1, strlen(ss) + 1)
  • @MOehm strlen(ss) + 1 : +1 不是必需的。
  • @BLUEPIXY:是的。我想包括空终止符,但忘记了第一个字符没有移动,因此 -1 和 +1 相互抵消。很好的收获。

标签: c linux string gcc strcpy


【解决方案1】:

来自strcpy(3) 手册:

   The  strings  may  not overlap, and the destination string dest must be
   large enough to receive the copy.  Beware  of  buffer  overruns!   (See
   BUGS.)

你应该使用memmove(3):

    memmove(ss, ss+1, strlen(ss));   // remove first symbol - quote

...而不是...

    strcpy(ss, ss+1);   // remove first symbol - quote

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多