I am surprised this compiles without any warning:
int main()
{
*"abc" = '\0';
}
with gcc main.c -Wall -Wextra
and clang main.c -Weverything
.
Why is there no warning for this ? Is there any way this could not raise a segmentation fault ?
In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or (in C programs) accidentally using a variable's value as an address (see the scanf example below).
The only standard way in which a SIGSEGV occurs is with the call raise(SIGSEGV); . If this is the source of a SIGSEGV, then it is obviously recoverable by using longjump.
You can use -Wwrite-strings
to get a warning for this code in GCC. From the GCC documentation:
-Wwrite-strings
When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer will get a warning. These warnings will help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it will just be a nuisance. This is why we did not make -Wall request these warnings.
When compiling C++, warn about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs.
"Is there any way this could not raise a segmentation fault ?" -> It is undefined behavior to modify a string litteral. So anything could happen, including not segfaulting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With