c - strcpy and string presentation in memory -


i have program this(x86_64 gnu/linux)

int main() {     char s[] = "123456789";     char d[] = "123";     strcpy(d, s);      printf("%p, %0p\n", s, d);     printf("%s, %s", s, d);      return 0; } 

and output : 0xeb6d2930 0xeb6d2910 123456789 123456789 little confused result think program in memory this:

  • '9','\0' . .
  • '5','6','7','8'
  • 0x7fff813af310: '1','2','3','4'
  • 0x7fff813af300: '1','2','3','\0'

so result should *s = "789", *d = "123456789"

could guys explain why result isn't thought? changed format specifier %p print address of d , s know s , d overlapped there not enough space d hold s may lead undefined behaviour,but anyway wondering why result *s = "123456789" *d = "123456789"

from output show address layout , it's initial content seem be:

       offset 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f   d: 0xeb6d2910 30 31 32 00 xx xx xx xx xx xx xx xx xx xx xx xx | 1 2 3 . . . . . . . . . . . . .    0xeb6d2920 xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx | . . . . . . . . . . . . . . . . s: 0xeb6d2930 30 31 32 33 34 35 36 37 38 39 00 xx xx xx xx xx | 1 2 3 4 5 6 7 8 9 . . . . . . .  

after strcpy(d, s):

       offset 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f   d: 0xeb6d2910 30 31 32 33 34 35 36 37 38 39 00 xx xx xx xx xx | 1 2 3 4 5 6 7 8 9 . . . . . . .     0xeb6d2920 xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx | . . . . . . . . . . . . . . . . s: 0xeb6d2930 30 31 32 33 34 35 36 37 38 39 00 xx xx xx xx xx | 1 2 3 4 5 6 7 8 9 . . . . . . .  

however, d fewer memory had been allocated used during strcpy() code invokes undefeind behaviour.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -