Compile-time error and runtime error

I am confused why the compiler gives

const char s[]="hello";
s[2]='t';                 // Compile Time Error

char *t = "hello";
*(t+2)='u';              // Run time Error

I assume that in both cases the compiler should give a compile-time error. Can someone tell me a specific reason for this to be so?

+5
source share
4 answers

In the first case, you write const, and the compiler notices this and may reject it.

In the second case, it tis a pointer to non-constant char, so you can dereference it and write to *(t+2). However, since it is tinitialized with a pointer to a read-only segment, you get a segmentation violation at runtime.

, . .

P.S. ( Frama-C) . , GCC, . MELT, ( , ).

+6

.

const char. .

, , , . , . .


, . char[] .

, - char[], const char[] C89 C99 [ , C11, , ]. , , undefined .


, , , -Wwrite-strings, gcc (g++ ) .


.

+6

: char *t = "hello";, t - , , , . , .

: const char s[]="hello";, s - , , const, , ( , const, ).

Using constwhen you do not want your string to be changed is good because a compilation error occurs that is better than a runtime error.

+3
source

Consider the following sequence of statements:

char *t = "hello";
char s[5];
t = s;
*(t+2)='u';

In this series of claims, a runtime error will not be indicated because the statement *(t+2)='u';is not invalid. It tries to change the location of const (read-only) memory in your case, but the compiler does not know if an access violation will occur.

+2
source

All Articles