我很惊讶这个编译没有任何警告:
int main()
{
*"abc" = '\0';
}
使用 gcc main.c -Wall -Wextra
和 clang main.c -Weverything
。
为什么没有警告呢?有什么办法不会引发段错误吗?
最佳答案
您可以使用 -Wwrite-strings
在 GCC 中获取此代码的警告。来自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.
“有什么办法不会引发段错误吗?” -> 修改字符串文字是未定义的行为。所以任何事情都可能发生,包括不发生段错误。
关于c - 没有明显段错误的编译器警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099374/