-2

strcpy function in CodeBlocks with MinGW is not behaving properly. It is modifying the constant string when the Destination has less space than source string. According to standards, if Destination has less space than source the behavior is undefined, but why Source(S), which is a accepted as constant by strcpy function, is getting modified?

#include<string.h>
#include<stdio.h>
int main(){
    char S[]="Computer";
    char D[]="";
    strcpy(D,S);
    printf("%s\n",S);
    return 0;
}

Output: When size of D(Destination) is equal or more than size of S(source)

Output: When size of D is less than size of S

Output: Omputer [When size of D is not specified]

skyconfusion
  • 123
  • 8
  • You mean,constant string can also be modified!? – skyconfusion Jan 25 '16 at 05:52
  • 2
    Why do you have any expectation on **undefined** behaviour? If it is undefined then anything can happen. – kaylum Jan 25 '16 at 05:53
  • It's not a constant string. You use a constant string to initialise a char array. The char array itself is not a constant string. It is a char array of length `strlen("Computer")+1` and is modifiable. – kaylum Jan 25 '16 at 05:54

2 Answers2

1

It's pointless trying to make sense of undefined behavior. By definition, the behavior is "undefined".

My guess is that the memory allocated for S and D in the stack frame is as follows:

| D  |                S                   |
+-- -+---+---+---+---+---+---+---+---+----+
| \0 | C | o | m | p | u | t | e | r | \0 |
+-- -+---+---+---+---+---+---+---+---+----+

When you modify D beyond the valid limits, you end of modifying the contents of S.

While this is potentially true for your platform, it is not guaranteed to be true on another platform. Bottom line: don't count on a specific behavior when the standard clearly says it is undefined behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Understood the point. Strcpy is not modifying, it is just copying to D and S just has null left. I will try on other platforms also. But on Windows only with Cygwin GCC it works normal,doesn't modify source. – skyconfusion Jan 25 '16 at 06:08
0

In fact, by choosing a S > D, you are so close to create an buffer overflow. In strcpy(3) man page in my system (FreeBSD 10.2-RELEASE), there is the note below

SECURITY CONSIDERATIONS
     The strcpy() function is easily misused in a manner which enables mali-
     cious users to arbitrarily change a running program's functionality
     through a buffer overflow attack.

C does not make any bounds checking, and expects the programmer to do so. You may be, or may not be overwriting other buffer, totally depends on your compiler implementation.

As stated in comments and other posts, you cannot expect an Undefined Behaviour to follow a defined pattern.

fnisi
  • 1,181
  • 1
  • 14
  • 24