没有编译器警告明显的段错误

前端之家收集整理的这篇文章主要介绍了没有编译器警告明显的段错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很惊讶这个编译没有任何警告:
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是未定义的行为.所以任何事情都可能发生,包括不分裂.

原文链接:https://www.f2er.com/c/117843.html

猜你在找的C&C++相关文章