Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

strcpy not went expected in wsl

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading