I have a case where I initialize a char pointer with a string. I get some behaviour that works in one case, but not the other. I will explain with 3 samples of code:
The first code is this:
#include <stdio.h>
int main(void) {
char* f = "test";
printf("%s", f);//prints "test"
}
This code works fine, the point of including it is to show that we can initialize a char pointer with a string and print it fine.
The second code is this:
#include <stdio.h>
void strcpy(char* dst, char* src) {
int i = 0;
do {
*(dst + i) = *(src + i);
} while (*(src + (i++)));
}
int main(void) {
char first[] = "test2";
char second[] = "test3";
strcpy(second, first);
printf("%s", second); //prints "test2"
}
This code also works fine. The point of including it is because the next line of code will not work.
The third code is this:
#include <stdio.h>
void strcpy(char* dst, char* src) {
int i = 0;
do {
*(dst + i) = *(src + i);
} while (*(src + (i++)));
}
int main(void) {
char first[] = "test4";
char *second = "test5"; //ONLY THIS LINE IS CHANGED
strcpy(second, first);
printf("%s", second); //PRINTS NOTHING
}
Do you see why the third code prints nothing? It is just the combined of the first and the second sample, so I can't see why it doesn't work?
char *second = "test5";
initializes second
to point to the first character of the array created by a string literal. About string literals, C 2018 6.4.5 7 says:
… If the program attempts to modify such an array, the behavior is undefined.
Since your program attempts to modify the array when it calls strcpy(second, first);
, the behavior of your program is not defined.
A common behavior of C implementations is to put the arrays of string literals in memory marked as read-only for the process, so attempting to modify such an array causes a memory access violation.
Compiler optimization may also cause other behaviors initially surprising to programmers as optimization may assume that no attempt to modify the array of a string literal occurs and hence may transform the program based on that assumption.