0

Why is the below code working in Visual Studio ?

char* str1 = "This is a test string";
strcpy_s(str1, strlen(str1), "replacing content");

My understanding is str1 is just a char* pointing to a string literal, and not to an array of chars. And in strcpy_s() (or strcpy()), char bytes are copied from src to dst array.

In the above code, isn't strcpy() trying to overwrite a string literal ? If yes, then why is the code compiling ?

additional info

Not only is the code compiling, I can see the new string getting copied.

void stringCopy_demo() {    
    char* str1 = "1234567890"; //len = 10   
    printf("%s \n", str1);
    strcpy_s(str1, strlen(str1), "content");
    printf("%s \n", str1);  
}

ouput

1234567890
content
TanM
  • 99
  • 1
  • 6
  • 3
    If the code compiles, have you tried to run it? – medalib Apr 14 '18 at 17:22
  • Just because it compiles doesn't mean it's "working"! – Tormund Giantsbane Apr 14 '18 at 17:24
  • Assuming that your code does compile, I think you need to change the question to "why does the C compiler allow me to use strcpy to overwrite a string literal"? – VA systems engineer Apr 14 '18 at 17:29
  • 3
    It is undefined behaviour. Anything may happen. That inludes "appearing to work" and "crashing" and also modifying the string literals `"string"` and `"test string"` that are used elsewhere in your code. – Jonathan Leffler Apr 14 '18 at 17:29
  • @NovaSysEng Thanks. I have changed the title as per ur suggestion. – TanM Apr 14 '18 at 17:31
  • [C11 §6.4.5 String literals ¶6,7](https://port70.net/~nsz/c/c11/n1570.html#6.4.5p6) says: _…The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. … If the program attempts to modify such an array, the behavior is undefined._ – Jonathan Leffler Apr 14 '18 at 17:35
  • Did the compiler give you a warning? – Arndt Jonasson Apr 14 '18 at 17:36
  • Use the `const` modifier to protect yourself, `const char* str1 = "This is a test string";`. Suppose `str1` was supplied as a function argument and the initialisation was by the function caller. It would be unreasonable to expect the compiler to know it is a string literal. But now, the compiler will object. – Weather Vane Apr 14 '18 at 17:38
  • Changed compiler to gcc. And Voila !!! Code crashes. – TanM Apr 14 '18 at 17:53
  • @TanM that is because you have *undefined behaviour*. This is not a value judgement about the code compilers produce - the results are unpredictable. What can be judged, is the warnings you are given by the compiler. – Weather Vane Apr 14 '18 at 18:27

1 Answers1

2

C99 string literals are char[], but modifying the array is undefined behaviour, see What is the type of string literals in C and C++? .

Many compilers have options to enable warnings for non-const usage, e.g gcc's -Wwrite-strings

Janne Husberg
  • 294
  • 1
  • 9