引用数组复合文字的一生 [英] Lifetime of referenced compound array literals
问题描述
我最近才知道,我可以实际使用中引用C,我觉得这很有用复合文字数组,但我不明白它是如何工作的。
I only recently learned that I can actually use references to compound literal arrays in C, which I find useful, but I don't quite understand how it works.
例如,说我使用的功能,以避免声明一个变量调用一些套接字接口功能,我不计较回报名称的长度,像这样的:
For instance, say that I use the feature to avoid having to declare a variable for a call some socket interface function where I don't care about the return name length, like this:
int sockfamily(int fd)
{
struct sockaddr_storage ss;
getpeername(fd, (struct sockaddr *)&ss, (socklen_t [1]){sizeof(ss)});
return(ss.ss_family);
}
显然,的sizeof(SS)
需要实际存储在堆栈上,以便一个指向它要传递给 getpeername 因此code>,堆栈空间上必须分配并保留作该用途,但这种分配的生命周期是什么?我多久可以信任它保持分配呢?
Clearly, sizeof(ss)
needs to actually be stored on the stack in order for a pointer to it to be passed to getpeername
, and space on the stack must therefore be allocated and reserved for that purpose, but what is the lifetime of this allocation? How long can I trust it to remain allocated?
综观GCC的汇编输出,我观察到,如果我把调用 getpeername
在一个循环中,分配不进行循环的多次迭代求生存,但其他情况的话,可能会造成什么就不复存在了?
Looking at the assembly output of GCC, I observe that if I put the call to getpeername
in a loop, the allocation does not survive for multiple iterations of the loop, but what other conditions, then, might cause it to cease to exist?
推荐答案
一个的复合文字的函数中定义已与包含它的块关联的自动生命周期(即相同的寿命作为一个变量声明在同一水平上)。这是在标准,段落6.5.2.5p5指定
A compound literal defined within a function has automatic lifetime associated with the block that contains it (i.e. the same lifetime as a variable declared on the same level). This is specified in the standard, paragraph 6.5.2.5p5.
int f() {
for (int i = 0; i < 10; ++i) {
int *j = (int []){i}; // storage duration of loop body
}
}
这实际上意味着,文字的化合物,相当于申报并在同一范围内初始化的变量:
This essentially means that a compound literal is equivalent to a variable declared and initialized in the same scope:
int f() {
for (int i = 0; i < 10; ++i) {
int __unnamed[] = {i};
int *j = __unnamed;
}
}
请注意,如果通过复合文字的任何地方他们的三分球可能持续过去他们的一生:
Take care if passing compound literals anywhere their pointers could persist past their lifetime:
int f() {
int *p;
if (1) {
p = (int []){0, 1, 2};
assert(p[0] == 0);
}
// *p is undefined
}
这篇关于引用数组复合文字的一生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!