gpt4 book ai didi

c++ - 与返回硬编码字符串文字的函数一起存储的字符串在哪里?

转载 作者:太空宇宙 更新时间:2023-11-04 04:22:43 25 4
gpt4 key购买 nike

我在 C/C++ 代码中看到过:

char * GetName()
{
return "Aurian";
}

幕后到底发生了什么? "Aurian" 存储在内存中的哪个位置,这样当我离开 GetName() 范围时它仍然存在,并且我得到一个 char * 到它?我猜它不遵循与返回 int 相同的规则。这与什么有关

char * name = "Aurian";

这个实现依赖吗?另外,GetName() 会被编译成 "Aurian" 吗?

This thread似乎暗示某种跳转表可能用于所有字符串文字,无论如何对于 GCC。

最佳答案

看起来字符串常量存储在数据段的只读部分(与其他非零初始化静态变量一起)。检查组装!

我编译这个

#include<stdio.h>
char * GetName()
{
return "Aurian";
}
int main()
{
printf("%s", GetName());
return 0;
}

程序集看起来像

    .section    .rodata
.LC0:
.string "Aurian"
.text
.globl GetName
.type GetName, @function
GetName:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $.LC0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size GetName, .-GetName
.section .rodata
.LC1:
.string "%s"
.text
.globl main
.type main, @function
main:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $0, %eax
call GetName
movq %rax, %rsi
movl $.LC1, %edi
movl $0, %eax
call printf
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc

关于c++ - 与返回硬编码字符串文字的函数一起存储的字符串在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856870/

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