I have been doing this exercise of exploring strings in c programming. I found that we can assign a string literal to a pointer also (Like in the code mentioned here!)
#include <stdio.h>
int main(void)
{
char msg1[] = "Hello";
char *msg2 = ", Welt";
printf("the string at msg1 is :%s\n", msg1);
printf("the string at msg2 is :%s\n", msg2);
printf("Address of the msg1 is: %p\n",&msg1);
printf("Address of the msg2 is: %p\n",&msg2);
printf("Value of the msg1 is: %p\n",msg1);
printf("Value of the msg2 is: %p\n",msg2);
msg1[1] = 'G';
msg2[2] = 'X';
printf("Value of the msg1 is: %p\n",msg1);
printf("Value of the msg2 is: %p\n",msg2);
return 0;
}
now when I execute this I get:
C:\Users\ADMIN\Desktop>test
the string at msg1 is :Hello
the string at msg2 is :, Rohit
Address of the msg1 is: 0061FF1A
Address of the msg2 is: 0061FF14
Value of the msg1 is: 0061FF1A
Value of the msg2 is: 00405064
i.e. The last two lines are not even printed! (same results in any platform)
My understanding and my question: I understand that I am assigning a ROM address to the pointer variable called: char *msg2, and am assigning a String Literal: ", Welt" to it. I also know that the FLASH controller at ROM will not allow this Write operation unless there is like a "special permission".(I'm still learning about these kind of processes).
But the thing is that: why are the print messages after that "illegal ROM-write process" are not being executed? is it because the the compiler ignores the instructions after that "illegal ROM-write process" ?
I know that we should NOT play around with ROM access like this in a program, rather use a:
char const *msg2 = ", Welt"; //which will give us an error incase we change something.
SORRY, I've just started Stack Overflow - I will learn to be more professional in the upcoming days
CodePudding user response:
msg2[2] = 'X';
is undefined behavior (UB) as it attempts to change a string literal.
Anything may happen including <messages after that "illegal ROM-write process" are not being executed>.
is it because the the compiler ignores the instructions after that "illegal ROM-write process" ?
If this was true, then that would be defined behavior. It has the possibility of being true today and not tomorrow. Anything may happen as that what UB is all about - uncertainty.