0

In some project i have piece of C code that works wrong, but only with particular input string. I compile this piece only:

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

The result is

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

So i get 'abcdefhhijkl' instead of 'abcdefghijkl'. Where i am wrong? Thanks.

P.S. I hope there is no any multibyte/Unicode chars in my code, but additional check may be need.

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
user2223633
  • 151
  • 1
  • 1
  • 10
  • 7
    The source and destination strings in `strcpy` may not overlap. You could try `memmove(ss, ss+1, strlen(ss) + 1)`. – M Oehm Sep 22 '15 at 12:47
  • 2
    @MOehm `strlen(ss) + 1` : `+1` is not required. – BLUEPIXY Sep 22 '15 at 13:00
  • 1
    @BLUEPIXY: True. I wanted to include the null terminator, but forgot that the first char isn't moved, so that the -1 and +1 cancel each other out. Good catch. – M Oehm Sep 22 '15 at 13:03

1 Answers1

2

From the strcpy(3) manual:

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

You should use memmove(3):

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

... instead of ...

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