27

I've come across a snippet of code that to me should crash with a segmentation fault, and yet it works without a hitch. The code in question plus relevant data structure is as follows (with associated comment found right above):

typedef struct {
  double length;
  unsigned char nPlaced;
  unsigned char path[0];
}


RouteDefinition* Alloc_RouteDefinition()
{
  // NB: The +nBags*sizeof.. trick "expands" the path[0] array in RouteDefinition
  // to the path[nBags] array
  RouteDefinition *def = NULL;
  return (RouteDefinition*) malloc(sizeof(RouteDefinition) + nBags * sizeof(def->path[0]));
}

Why does this work? I gather that the sizeof the char* will resolve to the size of the pointer on the given architecture, but shouldn't it crash and burn while dereferencing a NULL-pointer?

3
  • Joachim's right (+1). While sizeof is likely internal to the compiler, you can often observe this kind of language behaviour in an interesting and tangible form by looking at your Standard library's offsetof implementation: it probably takes the address of a data member of a fictitious object made by casting a 0/NULL pointer... that's even closer to the precipice than sizeof, but entirely legal. Nov 5, 2013 at 9:32
  • sizeof(def->path[0]) is 1 by definition, so the return statement collapses to the much more readable: return malloc(sizeof(RouteDefinition) + nBags); Nov 5, 2013 at 9:40

3 Answers 3

21

Why does this work?

This works because sizeof is a compile time construct, with the exception of variable length arrays is not evaluated at all. If we look at the C99 draft standard section 6.5.3.4 The sizeof operator paragraph 2 says(emphasis mine):

[...] The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

we also see the following example in paragraph 5 which confirms this:

double *dp = alloc(sizeof *dp);
       ^^^                ^
                          |                                 
                          This is not the use of uninitialized pointer 

At compile time the type of the expression with be determined in order to compute the result. We can further demonstrate this with the following example:

int x = 0 ;
printf("%zu\n", sizeof( x++ ));

which won't increment x, which is pretty neat.

Update

As I note in my answer to Why does sizeof(x++) not increment x? there is an exception to sizeof being a compile time operation and that is when it's operand is a variable length array(VLA). Although I did not previously point it out the quote from 6.5.3.4 above does say this.

Although in C11 as opposed to C99 it is unspecified whether sizeof is evaluated or not in this case.

Also, note there is a C++ version of this quesiton: Does not evaluating the expression to which sizeof is applied make it legal to dereference a null or invalid pointer inside sizeof in C++?.

10

The sizeof operator is a pure compile-time operation. Nothing is done runtime, which is why it works fine.

By the way, the path member is not actually a pointer, so it can't technically be NULL.

1
  • 9
    The exception to sizeof being compile time is with VLAs. Nov 6, 2013 at 15:47
3

Stating that sizeof is a purely compile-time construct (as currently existing answers do) is not entirely accurate. Since C99, sizeof is not a purely compile time construct. The operand of sizeof is evaluated at run-time of the operand type is a VLA. The answers posted so far seem to ignore that possibility.

Your code is fine, since it does not involve any VLA. However, something like this can be a different story

unsigned n = 10;
int (*a)[n] = NULL; // `a` is a pointer to a VLA 

unsigned i = 0;
sizeof a[i++];      // applying `sizeof` to a VLA

According to the C99 standard, the argument of sizeof is supposed to be evaluated (i.e. i is supposed to get incremented, see https://ideone.com/9Fv6xC). However, I'm not entirely sure that the null-point dereference in a[0] is supposed to produce undefined behavior here.

5
  • Are there any cases in which requiring any observable behaviors from the argument of sizeof improves the expressiveness of the language? The only situation in which values computed within sizeof could affect its result is when it is applied to a VLA type which is created within the sizeof expression, and I can think of no reason where allowing that enhances the expressiveness of the language. Note, btw, that even typedef statements can generate executable code!
    – supercat
    Jun 11, 2015 at 20:27
  • @supercat even typedef statements can generate executable code!. Could you give an example? Thanks!
    – a3f
    Feb 20, 2016 at 12:53
  • @supercat even typedef statements can generate executable code!. Could you give an example? Thanks!
    – pmor
    Jan 9, 2023 at 9:08
  • @pmor: Sure. Given the declaration int doSomething(void);, the block-scope declaration typedef int silliness[doSomething()]; will invoke doSomething().
    – supercat
    Jan 9, 2023 at 15:49
  • @supercat Indeed, typedef (pointer to) VLA requires evaluation of the size expression.
    – pmor
    Jan 10, 2023 at 10:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.