考虑以下代码:
const char* someFun() {
// ... some stuff
return "Some text!!"
}
int main()
{
{ // Block: A
const char* retStr = someFun();
// use retStr
}
}
Run Code Online (Sandbox Code Playgroud)
在函数中someFun()
,"Some text!!"
存储的位置(我认为它可能在ROM的某个静态区域)以及它是什么范围 一生?
指向的内存是否会在retStr
整个程序中被占用,或者在块A退出后被释放?
对于大学课程,我喜欢比较使用 gcc/clang 与汇编编写和编译的功能相似程序的代码大小。在重新评估如何进一步缩小某些可执行文件的大小的过程中,当我 2 年前组装/链接的完全相同的汇编代码在重新构建后现在已经增长了 10 倍以上时,我简直不敢相信自己的眼睛适用于多个程序,不仅是 helloworld):
$ make
as -32 -o helloworld-asm-2020.o helloworld-asm-2020.s
ld -melf_i386 -o helloworld-asm-2020 helloworld-asm-2020.o
$ ls -l
-rwxr-xr-x 1 xxx users 708 Jul 18 2018 helloworld-asm-2018*
-rwxr-xr-x 1 xxx users 8704 Nov 25 15:00 helloworld-asm-2020*
-rwxr-xr-x 1 xxx users 4724 Nov 25 15:00 helloworld-asm-2020-n*
-rwxr-xr-x 1 xxx users 4228 Nov 25 15:00 helloworld-asm-2020-n-sstripped*
-rwxr-xr-x 1 xxx users 604 Nov 25 15:00 helloworld-asm-2020.o*
-rw-r--r-- 1 xxx users 498 Nov 25 14:44 helloworld-asm-2020.s
Run Code Online (Sandbox Code Playgroud)
汇编代码是:
.code32
.section …
Run Code Online (Sandbox Code Playgroud) 我一直想知道,C++中的字符串常量有多长.例如,如果我在函数内部创建了一些const char*str ="something",那么返回str的值是否安全?
我写了一个示例程序,看到这样的返回值仍然存储了该字符串,我感到非常惊讶.这是代码:
#include <iostream>
using namespace std;
const char *func1()
{
const char *c = "I am a string too";
return c;
}
void func2(const char *c = "I'm a default string")
{
cout << c << endl;
}
const int *func3()
{
const int &b = 10;
return &b;
}
int main()
{
const char *c = "I'm a string";
cout << c << endl;
cout << func1() << endl;
func2();
func2("I'm not a default string");
cout …
Run Code Online (Sandbox Code Playgroud)