Programming in C, are there any techniques one can use to avoid (or at least minimize the likelihood of) casting a void * to the wrong pointer type by mistake? I’m working on a program that parses several different types of CSV datafiles and stores the fields into specific data structures for processing. For example, the records of one of the data files is stored in a hash table; data from another file is stored in a directed graph.
I’d like to create one main parsing function that reads in a record of fields from the file and passes each record to a function that tokenizes the fields and stores them in the appropriate data type. Instead of creating separate parsing/tokenizing functions for each file-type, I wanted to create a generic function to do this. In my design, the calling function would pass a record of fields, a function pointer to the tokenizer applicable to the data-file, and a void* pointing to a node of the destination data structure applicable to the data-file.
What I want to know is whether there is any way to ensure that the user does not mistakenly call the parsing function with a mismatched tokenizer / data structure. (By using the pointer to void, the compiler is certainly helpless here.) Or, if there are no such techniques, are there any effective exception-handling methods to catch this error and prevent major problems (e.g., sigfaults)?
I’d like the code to be as portable as possible.
Any thoughts? I’m not married to this algorithm, if someone has a better idea I’m open to it.
One possibility is to create a set of very thin wrapper functions that abstract away the type-safety issues:
Now all the potentials for typos are restricted to a single location, where mistakes should be easier to find due to the symmetry.
If you’re feeling especially naughty, you could use a macro to simplify the generation of these wrapper functions:
This minimises the probability of typos, but increases the chance of confusing the debugger/IDE!