strcpy not went expected in wsl

Advertisements

I’m writing c code using wsl with gcc compiler.And I tried to delete a space in front of a c-string with strcpy and got a strange result.
The string I tried to modify is s = {‘ ‘,’e’,’h’,’c’,’o’ ,’\0′};And I use a pointer temp to point at the "e"in the string and then I use strcpy(s,temp) to delete the space.BUT the result I get is ecoo,not echo.

#include  <stdio.h>
#include  <unistd.h>
#include  <string.h>
int main(){
    char a[256];
    a[0] = ' ';
    a[1] = 'e';
    a[2] = 'h';
    a[3] = 'c';
    a[4]  = 'o';
    a[5] = '\0';
    char* temp = a;
    temp ++ ;
    printf("%s\n",temp);
    strcpy(a,temp);
    printf("%s\n",a);
    
}

I tried to debug in the program and temp is indeed "echo"but the result is ecoo.
The code went as expected in the windows system in visual studio and vscode.
And I also tried different string length and I found out the code went well when the length of the string is 3,7.
enter image description here

>Solution :

Your code is invalid. From https://en.cppreference.com/w/c/string/byte/strcpy :

The behavior is undefined if the strings overlap.

temp is equal to a + 1 – they overlap. strcpy(a, a + 1) is not valid.

Leave a ReplyCancel reply