0

This is the problem : I have two string s1 and s2. I want write a function that get one of the two string a override the other string.

I can do this with this code (C) :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void modifica_overflow(char *s){
    printf("\n\nAdress where I want write -> %p", (s + strlen(s) + 1));
    strcpy((s + strlen(s) + 1 ), s);
    return;
}

int main(void) {
    char s1[] = "Name";
    char s2[] = "emaN";

    printf("\ns1 Adress -> %p", (void*)s1);
    printf("\ns2 Adress -> %p ", (void*)s2);

    printf("\n\nBefore s1 : %s s2 : %s", s1, s2);
    modifica_overflow(s2);
    printf("\n\nAfter s1 : %s s2 : %s", s1, s2);

    return EXIT_SUCCESS;
}

This is output :

s1 Adress -> 0061FF2B
s2 Adress -> 0061FF26 

Before s1 : Name s2 : emaN

Adress where I want write -> 0061FF2B

After s1 : emaN s2 : emaN

Perfect work!

But with this code I have a crash

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void modifica_overflow(char *s){
    printf("\n\nAdress where I want write -> %p", (s + strlen(s) + 1));
    strcpy((s + strlen(s) + 1 ), s);
    return;
}

int main(void) {
    char *s1 = "Name";
    char *s2 = "emaN";

    printf("\ns1 Adress -> %p", (void*)s1);
    printf("\ns2 Adress -> %p", (void*)s2);

    printf("\n\nBefore s1 : %s s2 : %s", s1, s2);
    modifica_overflow(s1);
    printf("\n\nAfter s1 : %s s2 : %s", s1, s2);



    return EXIT_SUCCESS;
}

If I comment this line strcpy((s + strlen(s) + 1 ), s); this is output :

s1 Adress -> 00405086
s2 Adress -> 0040508B

Before s1 : Name s2 : emaN

Adress where I want write -> 0040508B

After s1 : Name s2 : emaN

Why second program doesn't work?

SGiux
  • 619
  • 3
  • 10
  • 34

1 Answers1

0

Do you understand the difference between the pointer and the array?

The fist case: You have the UB there as you write outside the array bounds. But the array is in the RW memory and you were lucky enough to do not get the SEGFAULT.

The second case - pointer to string literal in the RO memory. You cant write there and you get the instant error

Both are wrong@!@!! You need a good C book first

0___________
  • 60,014
  • 4
  • 34
  • 74
  • I know that both are wrong but I want write outside the array bounds voluntarily. This is only a test. The C isn't memory save and I can to do this. I only don't know that string literal are not editable. – SGiux Oct 27 '17 at 07:10
  • String literals are read only. in the first case the literal is copied into the array – 0___________ Oct 27 '17 at 07:55