我很惊讶这个编译没有任何警告:
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.
“有什么办法可以解决分段错误吗?” – >修改字符串litteral是未定义的行为.所以任何事情都可能发生,包括不分裂.