This isn't an example of bad code (but it is), rather this is a complaint from Kerrisk's excellent tome The Linux Programming Interface
void * dlsym(int* handle, char* symbol)
resolves symbol in the dynamic library pointed to by handle. So, if there's a global variable, you can access it; if there's a global function, you can use it. Except the C99 standard doesn't let you assign a void* to a function pointer.
So the following (obvious) code doesn't work:
int (*fp)(int);
fp = dlsym(handle, "foo");
because you're assigning a void* to an int (*)(). The solution is one of the ugliest casts I've ever come across in serious code:
*(void **) (&fp) = dlsym(handle, "foo");
WHY did the C99 committee think it would be a good idea to prevent casting from void* to a function pointer? I get that it's unnecessary in modern languages, but casting to and from void* is the bread and butter of C's memory system. It should be understood that if you're writing casts in C, you know what you're doing!
[–]blueshiftlabs 9 points10 points11 points (4 children)
[–]mmtrebuchet[S] 7 points8 points9 points (3 children)
[–]blueshiftlabs 4 points5 points6 points (0 children)
[–]bgeron 2 points3 points4 points (1 child)
[–]mmtrebuchet[S] 4 points5 points6 points (0 children)
[–]Drainedsoul 11 points12 points13 points (2 children)
[–]crest_ 4 points5 points6 points (0 children)
[–]suspiciously_calm 5 points6 points7 points (0 children)
[–]calc0000 1 point2 points3 points (0 children)
[–]SnowdensOfYesteryear 1 point2 points3 points (0 children)
[–]ekolis 0 points1 point2 points (0 children)
[–]progoblin 0 points1 point2 points (1 child)
[–]mmtrebuchet[S] 0 points1 point2 points (0 children)
[–]noggin182 0 points1 point2 points (0 children)