kingmohan45
kingmohan45

Reputation: 5

Without null char in second argument for strcpy() function is returning unexpected result. Why?

#include<stdio.h>
#include <string.h>
int main()
{
    char a[5];
    char b[2]="12";
    strcpy(a,b);
    printf("%s\n",a);
}

There is no null char in string b that is why the output is not as expected.
output : 12@
Why the output is coming like this only?

Upvotes: 0

Views: 454

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263277

Your program has undefined behavior.

Your array b contains { '1', '2' }. As you say, there is no null character in the array -- which means it doesn't contain a string.

strcpy's second argument must be a pointer to a string. You gave it a char* value that is not a pointer to a string.

In practice, strcpy will probably continue copying characters from the memory following b. That memory contains arbitrary garbage -- and even the attempt to access it has undefined behavior.

In a sense, you're lucky that you got output that is visibly garbage. If there had happened to be a null character immediately following your array in memory, and if your program didn't blow up trying to access it, it could have just printed 12, and you might not have known that your program is buggy.

If you want to correct your program, you can change

char b[2] = "12";

to

char b[] = "12";

The compiler will figure out how big b needs to be to hold the string (including the required terminating null character).

Upvotes: 1

dave
dave

Reputation: 103

strcpy keeps copying until it hits a null character (byte with value 0x00). It copies whatever it encounters on the way. In your case, memory after the array b happens to contain a byte with value 0x40 ('@') and then a byte with value 0x00.

Upvotes: 1

Related Questions