1

I've encountered something in a simple code test that started bothering me. I don't really understand the reason the program crashes before line with the strcpy function invocation.

So basically, can someone explain to me, why does this sample of code works correctly:

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

#define WORD ", sugar."
#define SIZE 40

int main(void){
    
    const char * source = WORD;
    char copy_of_arr[SIZE] = "Try me on the ring, brother.";
    char * w1;
    puts(source);
    puts(copy_of_arr);
    w1 = strcpy(copy_of_arr + 6, source);
    puts(copy_of_arr);
    puts(w1);


    return 0;
}

Result:

, sugar.
Try me on the ring, brother.
Try me, sugar.
, sugar.
> End

And this does not?:

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

#define WORD ", sugar."

int main(void){
    
    const char * source = WORD;
    char * copy_of_arr = "Try me on the ring, brother.";
    char * w1;
    puts(source);
    puts(copy_of_arr);
    w1 = strcpy(copy_of_arr + 6, source);
    puts(copy_of_arr);
    puts(w1);


    return 0;
}

Result:

, sugar.
Try me on the ring, brother.
> End

I think I don't understand the concept of C strings correctly. I know, that strcpy function needs to copy source with type const char * to type char*, but why it does not copy in the second sample (and crashes instead) if char copy_of_arr[SIZE] and char * copy_of_arr should be the same type?

todovvox
  • 170
  • 10
  • 3
    In the second one, `w1 = strcpy(copy_of_arr + 6, source);` is trying to modify a string literal. – Weather Vane Oct 10 '21 at 18:42
  • @WeatherVane can you correct me if (and where) I'm wrong? So basically, when program starts, it moves that string literal in static memory, and array copies that string literal to itself, having a copy in itself. And pointer basically points to the address where that string literal is. So C standard does not allow modifying the string literal directly, only through copies that are contained in arrays, etc. Am I right? – todovvox Oct 10 '21 at 19:01
  • 1
    In the first one, the string literal is copied to the array at run-time, and that array is modified. – Weather Vane Oct 10 '21 at 19:05
  • @WeatherVane oh, I see, I see. Thank you. The rest what I've said is right? – todovvox Oct 10 '21 at 19:06
  • 1
    The C18 Standard says in **6.4.5 String literals** *If the program attempts to modify such an array, the behavior is undefined.* In your case it caused a segfault, but it could do anything (or function as you hoped). – Weather Vane Oct 10 '21 at 19:29
  • @WeatherVane thank you very much for your help. You've helped a lot. Now I understand. Thank you. – todovvox Oct 10 '21 at 20:06

0 Answers0