Search code examples
windowscrashfunction-pointersd

Assigning a value to a non-static function pointer resulting in crash - WHY?


I have a function which is defined like this:

typedef void (*logprintf_t)(const char* format, ...);

logprintf_t logprintf

void my_function() {
   logprintf = cast(logprintf_t)0x12345;
}

and it causes the application to exit. However, if I make the logprintf be static (I've seen this trick somewhere), i.e.:

void my_function() {
   static logprint_t logprintf = cast(logprintf_t)0x12345;
} 

it doesn't crash.

Is it such a language rule thing or kind of bug? Why dmd doesn't warn be about this?


Solution

  • This looks like a bug, albeit an obscure bug in how DMD processes wrong code. It should be reported and fixed eventually, but will probably not be a high priority bug. A few points:

    1. The correct cast syntax in D is cast(logprintf_t) someValue, not the old C-style (logprintf_t) someValue. This is to make casts greppable. The compiler usually rejects the old syntax, so if it didn't, there's something awfully strange going on. The code doesn't compile for me, though, because the compiler doesn't allow C-style cast syntax.

    2. typedef is a buggy feature that's scheduled for deprecation and removal in D2. Therefore, you shouldn't use it. In D, typedefs are strong. In D, alias has equivalent semantics to C's version of typedef.

    3. I didn't even know the old C-style function pointer syntax compiled in D. The more idiomatic (and less likely to expose obscure compiler bugs) syntax is void function(const char* format, ...) logprintf_t.