Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: A glitch regarding the usual malloc() idiom Date: Tue, 19 Jul 2016 15:30:06 -0700 Organization: None to speak of Lines: 57 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="27238"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+vxD9kDsu0f1mSI4Ubex0X" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:zfauoAJn1ZEzKSfEfmTSLTXzgCQ= sha1:O4AJkYjrlaDiOdLeJCr8vhq6uNc= Xref: csiph.com comp.lang.c:90631 The widely (but not universally) accepted idiom for calling malloc() in C is: some_type *ptr = malloc(sizeof *ptr); or, if you want to allocate an array: some_type *ptr = malloc(N * sizeof *ptr); The expression `*ptr` dereferences an uninitialized pointer, but it's safe because the operand of `sizeof` is not evaluated. Well, almost. As I've just realized while following up to a post in another thread by BartC, the operand *is* evaluated if it's of a variably modified type. A simple example: #include int main(void) { int n = 10; int (*p)[n] = malloc(sizeof *p); } Here `p` is a pointer to a variable length array (VLA), so `*p` is of a variably modified type, so it's evaluated -- which causes undefined behavior. (I started a thread a while ago suggesting that it shouldn't actually be necessary to evaluate the operand, since all you need is the size. I don't intend to re-argue that. The standard says it's evaluated, so it's evaluated.) This is a fairly obscure corner case where the commonly recommended malloc() idiom causes undefined behavior. I've never seen real-world code that runs into this; if you're allocating dynamically-sized arrays using malloc(), you'll usually use a pointer to the element type. This is just a mildly interesting observation. (One not particularly relevant data point: When I compile and run the above using gcc, it appears to work "correctly". This is of course a valid consequence of undefined behavior.) To avoid the UB, you could write something like: #include int main(void) { int n = 10; typedef int vla[n]; vla *p = malloc(sizeof (vla)); } -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"