gpt4 book ai didi

c - 当我将字符串文字分配给非常量指针时,为什么我的 C 编译器不发出警告?

转载 作者:行者123 更新时间:2023-12-02 10:53:25 24 4
gpt4 key购买 nike

以下代码可以在 Xcode 11.3.1 中的默认设置下正常编译:

#include <stdio.h>

int main(int argc, const char * argv[]) {
char* thing = "123";
thing[2] = '4';
printf("%s\n", thing);
return 0;
}

但是,在运行时,代码在 thing[2] = '4' 上陷入 EXC_BAD_ACCESS 陷阱。 。我认为这是因为代表 "123" 的字节的内存被编译到我的程序的二进制文件中,在现代处理器/操作系统上被标记为 code rather than data 。 ( This answer 证实了这一点 - 更不用说反汇编中有一个 leaq 0x4d(%rip), %rsi ; "123" 行,将指针传递到相对于指令指针的地址!)

从自修改代码时代开始,C 允许这样做只是一个历史产物吗?我注意到我还可以分配 void* x = main;没有任何提示我正在丢弃修饰符。

This answer说:

According to the C99 rationale, there were people in the committee who wanted string literals to be modifiable, so the standard does not explicitly forbid it.

我可以阅读更多关于此问题的讨论吗?更实际的是,有没有办法告诉 clang 和/或 gcc 标记此类分配(即使它们实际上没有被禁止)带有警告,而不编译为 C++?

最佳答案

你引用的答案是没有引用的观点,坦率地说是废话。想要在现代编译器中保持可编译性,无非就是不破坏大量现有的遗留 C 代码。

但是,如果您设置了必要的警告级别或选项,许多编译器发出警告。在 GCC例如:

-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 produces a warning. These warnings 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 is just 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.

CLANG 还有 -Wwrite-strings,其中是 -Wwriteable-strings 的同义词。

-Wwritable-strings

This diagnostic is enabled by default.

Also controls -Wdeprecated-writable-strings.

Diagnostic text:

warning: ISO C++11 does not allow conversion from string literal to A

C 编译的诊断文本有所不同 - 我只是引用手册。

在 GCC 中使用 -Wwrite-strings:

int main()
{
char* x = "hello" ;
return 0;
}

产生:

main.c:3:15: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]    

CLANG 产生:

source_file.c:3:15: warning: initializing 'char *' with an expression of type 'const char [6]' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]

关于c - 当我将字符串文字分配给非常量指针时,为什么我的 C 编译器不发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com