Regios
Regios

Reputation: 23

Segmentation fault of strcpy()

I was just going through C library functions to see what I can do with them. When I came across the strcpy function the code I wrote resulted in a segmentation fault and I would like to know why. The code I wrote should be printing WorldWorld. If I understood correctly, strcpy(x,y) will copy the contents of y into x.

 main() {
    char *x = "Hello";
    char *y = "World";
    printf(strcpy(x,y));
 }

Upvotes: 0

Views: 63

Answers (1)

zneak
zneak

Reputation: 138031

If it worked, the code you wrote would print "World", not "WorldWorld". Nothing is appended, strcpy overwrites data only.

Your program crashes because "Hello" and "World" are string constants. It's undefined behavior to attempt to write to a constant, and in your case this manifests as a segmentation fault. You should use char x[] = "Hello"; and char y[] = "World"; instead, which reserve memory on the stack to hold the strings, where they can be overwritten.

There are more problems with your program, though:

First, you should never pass a variable string as the first argument to printf: either use puts, or use printf("%s", string). Passing a variable as a format string prevents compilers that support type-checking printf arguments from doing that verification, and it can transform into a serious vulnerability if users can control it.

Second, you should never use strcpy. Strcpy will happily overrun buffers, which is another major security vulnerability. For instance, if you wrote:

char foo[] = "foo";
strcpy(foo, "this string is waaaaaay too long");
return;

you will cause undefined behavior, your program would crash again, and you're opening the door to other serious vulnerabilities that you can avoid by specifying the size of the destination buffer.

AFAIK, there is actually no standard C function that will decently copy strings, but the least bad one would be strlcpy, which additionally requires a size argument.

Upvotes: 2

Related Questions