Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a pointer, in C, is of a certain type?

Tags:

c

gcc

How do you check if a pointer is of a certain type?

Using sizeof is not sufficient.

I am trying to avoid putting id-numbers into my structs to identify their type. The assumption is that maybe gcc puts a struct definition somewhere in the process, and maps the definition to the allocated memory at a pointer. If this is true, I'd think there would be someway to check for a pointers type.

like image 852
Crazy Chenz Avatar asked Jun 04 '09 14:06

Crazy Chenz


1 Answers

Gcc does not put the structure definition anywhere in the runtime. This means you cannot as standard.

It can depend on what you are using the type information for. Two major applications might be:

  1. Debugging or similar runtime inspection
  2. Serialization and Deserialisation of datastructures

In the first case there information is often available stored in the symbols output by the compiler and attached to the executable (in many environments).

The implementation is platform specific and often means the compiler needs to be instructed to output this information. One example of a program doing this is gdb. Pointers still have to be typed correctly for this to be useful.

For serialisation types are often tagged with values like you suggest. These tags don't though have to be stored with the in-memory data. They can be added by the output routine.

like image 122
andygavin Avatar answered Oct 22 '22 09:10

andygavin