How strcpy works behind the scenes?

This may be a very simple question for some. I tried to understand how strcpy actually works behind the scenes. for example in this code

#include <stdio.h>
#include <string.h>
int main ()
{
  char s[6] = "Hello";
  char a[20] = "world isnsadsdas";
  strcpy(s,a);

  printf("%s\n",s);
  printf("%d\n", sizeof(s));
  return 0;
}

As I declare sas a static array with a size smaller than that of the source. I thought it did not print the whole word, but it printed world isnsadsdas. So, I thought this strcpy function could allocate a new size if the destination is smaller than the original. But now when I check sizeof (s), it is still 6, but it prints more than that. Wants what really works?

+5
source share
8 answers

undefined, . , , . strcpy ( ):

char *strcpy(char *d, const char *s)
{
   char *saved = d;
   while (*s)
   {
       *d++ = *s++;
   }
   *d = 0;
   return saved;
}

sizeof . strlen, , , . , , undefined - .

+11

http://natashenka.ca/wp-content/uploads/2014/01/strcpy8x11.png

strcpy , , . - , . , : http://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Call_stack_layout.svg/342px-Call_stack_layout.svg.png

FYI , , ( , , - "" ). , , locals , , , , . , , , . - , , .

, , , 6 5 , C \x00. strcpy , 0, , , . , \x00. , strcpy s , , , a , - "snsadsdas", , , , ).

, , , , ( , , ..), , , , , . , , - ram, .

strcpy, , , , . , , http://www.cplusplus.com/reference/cstring/strncpy/

, , , . , . , . , - , , , , , . .

+3

C , , , .

strcpy() , , undefined.

, strcpy, strcpy_s()

+2

undefined , , . .

sizeof, .

, strlen .

+1

, sizeof (s) . strlen(), . strcpy(), - , "Helloworld isnsadsdas"

#include <stdio.h>
#include <string.h>
main ()
{
  char s[6] = "Hello";
  char a[20] = "world isnsadsdas";
  strcpy(s,a);

  printf("%s\n",s);
  printf("%d\n", strlen(s));
}
+1

char *strcpy(char *p,char const *q)
{
   char *saved=p;

   while(*p++=*q++);//enter code here

   return saved;
}
0

/ null terminator character '\0', string/character.

strcpy() , '\ 0'.

printf() , '\ 0'.

sizeof()on the other hand, is not interested in the contents of the array, but only in its allocated size (how much it should be), not taking into account where the string / array of characters actually ends (how big it is).

Unlike sizeof (), there exists strlen()that he is interested in how long the string is (and not how long it should have been) and, therefore, counts the number of characters before it reaches the end (the character "\ 0"), where it stops (it does not include the character "\ 0").

0
source

All Articles