相关疑难解决方法(0)

为什么(仅)某些编译器对相同的字符串文字使用相同的地址?

https://godbolt.org/z/cyBiWY

我可以'some'在MSVC生成的汇编代码中看到两个文字,但只有一个有clang和gcc.这导致完全不同的代码执行结果.

static const char *A = "some";
static const char *B = "some";

void f() {
    if (A == B) {
        throw "Hello, string merging!";
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释这些编译输出之间的差异和相似之处吗?为什么即使没有请求优化,clang/gcc也会优化某些内容?这是某种未定义的行为吗?

我还注意到,如果我将声明更改为下面显示的声明,则clang/gcc/msvc根本不会"some"在汇编代码中留下任何声明.为什么行为不同?

static const char A[] = "some";
static const char B[] = "some";
Run Code Online (Sandbox Code Playgroud)

c++ string-literals string-interning language-lawyer

88
推荐指数
3
解决办法
6562
查看次数

两个字符串指向不同字符串文字的地址是相同的

#include<stdio.h>
#include<string.h>

int main()
{
    char * p = "abc";
    char * p1 = "abc";
    printf("%d %d", p, p1);
}
Run Code Online (Sandbox Code Playgroud)

当我打印两个指针的值时,它打印相同的地址.为什么?

c pointers literals

80
推荐指数
4
解决办法
6126
查看次数

不同的字符串如何具有相同的地址

我知道为了比较C中的两个字符串,您需要使用该strcmp()函数.但我试图将两个字符串与==运算符进行比较,并且它有效.我不知道如何,因为它只是比较两个字符串的地址.如果字符串不同,它应该不起作用.但后来我打印了字符串的地址:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* str1 = "First";
    char* str2 = "Second";
    char* str3 = "First";

    printf("%p %p %p", str1, str2, str3);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

00403024 0040302A 00403024
Process returned 0 (0x0)   execution time : 0.109 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)

怎么可能str1str3具有相同的地址?它们可能包含相同的字符串,但它们不是同一个变量.

c memory string pointers

19
推荐指数
3
解决办法
2981
查看次数

String Literal address across translation units

I'd like to ask if is it portable to rely on string literal address across translation units? I.e:

A given file foo.c has a reference to a string literal "I'm a literal!", is it correct and portable to rely that in other given file, bar.c in instance, that the same string literal "I'm a literal!" will have the same memory address? Considering that each file will be translated to a individual .o file.

For better illustration, follows an …

c c++ string pooling string-literals

7
推荐指数
1
解决办法
846
查看次数