是否可以覆盖使用#define 分配的地址下的数据?

Does data under address assigned using #define can be overwritten?

我很难理解#define 与指针结合时的工作原理。

这是我的伪代码:

#define ID "28"      // I need to keep it as string

int main()
{
    char * my_id = ID;
    ...
    ...
}

现在 my_id 实际指向什么?我没有为我的变量调用 alloc 也没有静态分配内存所以地址 my_id 下的数据可以被覆盖吗?

A​​ #define 只是进行文本替换。所以你所拥有的相当于:

char *my_id = "28";

这意味着my_id指向字符串常量"28"。字符串常量通常存储在只读数据部分中,因此 allocate/deallocate.

没有任何内容

经过预处理后,您的代码片段看起来像

 char * my_id = "28";

所以,my_id 指向字符串文字 "28".

对于字符串文字,它基本上是一个以空字符结尾的字符数组,具有 static 存储持续时间。但是,尝试修改 a(ny) 字符串文字会导致 undefined behavior.

引用 C11,章节 §6.4.5,字符串文字,第 6 段,

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence. [...]

和第 7 段,

[...] If the program attempts to modify such an array, the behavior is undefined.

所以,TL:DRmy_id指向字符串字面量,或者为了准确起见,它保存的是null的第一个元素的地址具有静态存储的终止数组,使用内容 "28".

进行初始化

字符串“28”将存储在您的可执行文件的一部分中。指针 my_id 将指向字符串“28”的地址。

编辑以删除对 'stack' 的错误引用。感谢评论者的澄清。