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

标签 c gcc segmentation-fault clang gcc-warning

我很惊讶这个编译没有任何警告:

int main()
{ 
    *"abc" = '\0';
}

使用 gcc main.c -Wall -Wextraclang 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/

相关文章:

c - scanf 在格式字符串中遇到空格时会做什么?

ios - UIView animateWithDuration 导致应用程序崩溃

c - 带有 C 预处理器指令的 Shell 脚本

c++ - 为什么 GCC 的 std::function 不使用对按值传递的参数的右值引用在其内部委托(delegate)之间传递它们?

linux - GDB 调试器错误

curl - 使独立 curl 导致段错误

c++ - 处理迭代器时由信号 SIGSEGV(地址边界错误)终止

c - 覆盖函数指针引发错误 : non-object type is not assignable

c - 如何将 char 指针值分配给整数/char 变量或数组

c - 我将如何创建自己的虚拟机?