public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
From: John Scott <jscott@posteo.net>
To: gcc-help@gcc.gnu.org
Subject: Re: Question about declaring an array in the stack on runtime
Date: Sat, 15 Jul 2023 10:49:40 +0000	[thread overview]
Message-ID: <f3cb718e895afce40e7d8afac07b03e9f755b051.camel@posteo.net> (raw)
In-Reply-To: <CAA_Li+tJ3DW_65naXfZKHERJpJExbdfwsoJDzQDXYBgiEvanKA@mail.gmail.com>


[-- Attachment #1.1: Type: text/plain, Size: 756 bytes --]

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 #1.2: This is a digitally signed message part --]
[-- Type: application/pgp-signature, Size: 228 bytes --]

[-- Attachment #2: smime.p7s --]
[-- Type: application/pkcs7-signature, Size: 5880 bytes --]

  reply	other threads:[~2023-07-15 10:50 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2023-07-15 10:43 James R T
2023-07-15 10:49 ` John Scott [this message]
2023-07-15 11:19 ` Xi Ruoyao
2023-07-15 12:57   ` James R T
2023-07-17 12:45 ` David Brown

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=f3cb718e895afce40e7d8afac07b03e9f755b051.camel@posteo.net \
    --to=jscott@posteo.net \
    --cc=gcc-help@gcc.gnu.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).