Re: Question about declaring an array in the stack on runtime

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sat, 2023-07-15 at 18:43 +0800, James R T via Gcc-help wrote:
> Is the conditional assignment to `arr` considered undefined
> behavior?
It's not the assignment that's the problem. The problem is that you're
using a compound literal, and a compound literal, like typical
automatically allocated variables, has a lifetime determined by its
scope.

In other words, the following:
if (some_var == 7) {
	arr = (unsigned int[7]){9, 10, 11, 12, 13, 14, 15};
}

is the same as
if (some_var == 7) {
	unsigned int baz[7] = {9, 10, 11, 12, 13, 14, 15};
	arr = baz;
}

I hope this makes the problem a little more obvious: after you leave the
'}', the array doesn't exist anymore, and arr is a dangling pointer to
an object that doesn't exist.

Attachment: signature.asc
Description: This is a digitally signed message part

Attachment: smime.p7s
Description: S/MIME cryptographic signature


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux