Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No compiler warning for obvious segfault

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 ?

like image 906
Bilow Avatar asked Sep 07 '17 14:09

Bilow


People also ask

What causes segfault in C?

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).

Is Sigsegv recoverable?

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.


1 Answers

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.

like image 160
Samuel Peter Avatar answered Oct 24 '22 15:10

Samuel Peter