C how strcpy works and Does it change the size of the original string?

5.1k views Asked by At

I have this code..

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

int main() {

    char a[6]="Hello";

    char b[]="this is mine";

    strcpy(a,b);

    printf("%d\n",sizeof(a));
    printf("%d\n",sizeof(b));

    printf("%s\n",a);
    printf("%s\n",b);

    printf("%d\n",sizeof(a));

    return 0;
}

6
13
this is mine
this is mine
6

I want to ask even I have copied the larger strng to a but its size is not changing but its contents are changing why?

Any help would be appreciated..

3

There are 3 answers

0
Iharob Al Asimi On

The size is not changing because for the compiler the array a has a fixed size and you cannot change it and no one can.

The contents are changing because there is no check performed for the bounds of the array, and it's working because of a coincidence. The code you posted has undefined behavior, and one of the possible outcomes is that it works as it is working in your case, but that will not necessarily always happen, add a variable to your main() function for example, and it might stop working.

0
AndrewGrant On

You cannot change the size of array A. strcpy is meant to be very fast, so it assumes that you, the user, passes a large enough array to fit the copied string. What you have done is override your array a's null terminator, and changed memory past where you have allocated. In many cases this will not work and cause your program to crash, but in a simple example it will run.

0
Eric meow meow On

The array a has a size of six char that cannot be changed. When you copy the other, longer string into the array, you overrun the array, introducing both instability and security concerns to the program.

When the computer loads the program into memory, the string literal hello is loaded into read-only memory as a constant, the space needed for the array is allocated in the stack memory, and finally, the string is copied into the array.

In this case, the source string overruns the destination array's length, as array a can hold 6 characters and the string literal that you are trying to copy to it is is 13 characters. This leads to a buffer overrun, which can lead to bugs, at the very least. Worse than that is the potential for information leaks and even more disastrous security consequences.

Please reference the strcpy man page:

Strcpy man page

In this example code, it minimally worked, but this is definitely something to avoid.