-1

I am executing this piece of code.

#include<stdio.h>
#include<string.h>
int main()
{


     char str1[]="himanshusaini";
     char str2[5];
     strcpy(str2,str1);
     printf("str1=%s\n str2=%s\n",str1,str2);
     return;

}

=========== Output is

str1=shusaini str2=himanshusaini

How the strcpy is working here, why the str1 is getting modified while str1 is the source string, and str2 is destination. On the other hand output of the str2 is full source string while size of str2 is only 5 byte.

Please assist me What is exactly happening here.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 1
    This is simply undefined behaviour - you are writing beyond the end of `str2`, so pretty much anything can happen. In this case you happened to stomp on the adjacent string `str1`. – Paul R Sep 15 '14 at 15:06
  • 1
    Numerous duplicates, e.g. [Why does strcpy "work" when writing to malloc'ed memory that is not large enough?](http://stackoverflow.com/questions/9919215/why-does-strcpy-work-when-writing-to-malloced-memory-that-is-not-large-enough) and [Why does this intentionally incorrect use of strcpy not fail horribly?](http://stackoverflow.com/questions/7139867/why-does-this-intentionally-incorrect-use-of-strcpy-not-fail-horribly) – Paul R Sep 15 '14 at 15:10

1 Answers1

-1

When I executed this code the result was like follow

str1=himanshusaini str2=himanshusaini

str1 is not changed as you said, However the reason for str2=himanshusaini, because char *strcpy(char *dest, const char *src)

dest -- This is the pointer to the destination array where the content is to be copied.

src -- This is the string to be copied.

Return Value This return a pointer to the destination string dest.

thus you have a pointer to the whole string which will be terminated by the special char '\0'

To only copy the first 5 char use stncpy

#include<stdio.h>
#include<string.h>
int main()
{


 char str1[]="himanshusaini";
 char str2[6];


 strncpy(str2,str1,5);
 str2[5] = '\0';   /* null character manually added */

 printf("str1=%s\n str2=%s\n",str1,str2);
 return 0;

}
  • add str2[5] = '\0'; after strncpy – Walid Ibrahim Sep 15 '14 at 15:18
  • 1
    This doesn't answer the question. See [the duplicate](http://stackoverflow.com/questions/7139867/why-does-this-intentionally-incorrect-use-of-strcpy-not-fail-horribly) for an explanation. And [`strncpy` is not a "safer" `strcpy`](http://the-flat-trantor-society.blogspot.com/2012/03/no-strncpy-is-not-safer-strcpy.html). – Keith Thompson Sep 15 '14 at 15:22