문제

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?

도움이 되었습니까?

해결책

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++?.

다른 팁

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top