字符串初始化函数和只读部分 [英] String initializer and read only section

查看:84
本文介绍了字符串初始化函数和只读部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组(函数的局部)和一个指针

Suppose that I have an array(local to a function) and a pointer

一个烧焦[] =aesdf的char * B =ASDF

我的问题是在前者的情况下字符串aesdf被存储在只读部分,然后复制到本地阵列或者是类似

My question is whether in the former case the string literal "aesdf" is stored in read only section and then copied on to the local array or is it similar to

烧焦一个[​​] = {'A​​','E','S','D','F','\\ 0'};

我认为在这种情况下,字符栈上,但在前面的情况下(炭一个[] =aesdf)的字符被从复制被直接创建只读部分到本地阵列

I think that in this case the characters are directly created on the stack but in the earlier case (char a[]="aesdf") the characters are copied from the read only section to the local array.

请问`aesdf的存在为可执行文件的整个生命?

Will `"aesdf" exist for the entire life of the executable?

推荐答案

从视图抽象和形式上看,每个字符串是静态存储持续时间一个独立的无名对象。这意味着,在初始化的char a [] =aesdf正式创建的文字对象aesdf,然后使用它初始化独立阵列 A ,也就是说,它不等同于的char * A =aesdf,其中一个指针,以点到的字符串直接。

From the abstract and formal point of view, each string literal is an independent nameless object with static storage duration. This means, that the initialization char a[] = "aesdf" formally creates literal object "aesdf" and then uses it to initialize the independent array a, i.e. it is not equivalent to char *a = "aesdf", where a pointer is made to point to the string literal directly.

然而,由于字符串文字的无名的对象,在烧焦一个[​​] =aesdf变种有没有办法进入独立aesdf对象之前或初始化之后。这意味着,有没有办法让你发现该对象是否确实存在。该对象的存在(或不存在)可以在不影响该程序的可观察到的行为。出于这个原因,实现了所有消除独立aesdf对象,并初始化 A 数组中的自由这导致了预期的正确结果,即如任何其他方式烧焦一个[​​] = {'A​​','E','S','D','F','\\ 0'} 一个烧焦[] = {'A​​','E',自卫队} 或别的东西。

However, since string literals are nameless objects, in the char a[] = "aesdf" variant there's no way to access the independent "aesdf" object before or after the initialization. This means that there's no way for you to "detect" whether this object actually existed. The existence (or non-existence) of that object cannot affect the observable behavior of the program. For this reason, the implementation has all the freedom to eliminate the independent "aesdf" object and initialize the a array in any other way that leads to the expected correct result, i.e. as char a[] = { 'a', 'e', 's', 'd', 'f', '\0' } or as char a[] = { 'a', 'e', "sdf" } or as something else.

这篇关于字符串初始化函数和只读部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆