0

The problem is, when the program steps to the line: stosb, it will display an error: "Program received signal SIGSEGV, Segmentation fault." I don't know why, any ideas?

Under ubuntu x86_64, using "gcc -o test test.c" to compile and link.

#include <stdio.h>

static inline char * strcpy(char * dest,const char *src)
{
    int d0, d1, d2;
    __asm__ __volatile__("1:\tlodsb\n\t"
                         "stosb\n\t"
                         "testb %%al,%%al\n\t"
                         "jne 1b"
                         : "=&S" (d0), "=&D" (d1), "=&a" (d2)
                         : "0" (src),"1" (dest)
                         : "memory");
    return dest;
}

int main(void) {
    char* src_main = "Hello_src";
    char* dest_main = "Hello_des";
    strcpy(dest_main, src_main);
    puts(src_main);
    puts(dest_main);
    return 0;
}

enter image description here

Searene
  • 25,920
  • 39
  • 129
  • 186

2 Answers2

1

The problem is that you're trying to overwrite a read-only section of memory, where the string literal "Hello_des" is stored. Don't do that.

The solution is to make the destination an array, which is writable:

char dest_main[32] = "Hello_des";

Of course, one wonders why you wrote this code, it's very pointless to initialize a string and then immediately strcpy() another string over it.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Don't use a string literal for the destination - string literals are commonly stored in a read-only section, i.e. they are effectively const. Change:

char* dest_main = "Hello_des";

to:

char dest_main[] = "Hello_des";

or just:

char dest_main[16];
Paul R
  • 208,748
  • 37
  • 389
  • 560