How to prevent arithmetic operations between different kinds of integers?

85 views Asked by At

I am working on a debugger (in C) which deals with embedded system whose memory has an addressable size of 16-bits. This means that at address x you have a 16-bits value, at (x + 1) you have another 16-bits value, etc. When working with data that comes from the target memory, I therefore have to convert the lengths between target bytes lengths and host bytes lengths. If I want to read 10 (16-bit) bytes from the target, I therefore have to allocate a 20 (8-bit) bytes in the debugger, which runs on the host.

A big number of bugs come from the fact that I forget to do these conversion, and I do semantically invalid arithmetic operations, such as adding an host memory address (i.e. the buffer allocated on my host) to a length in target bytes lengths. This makes no sense, and the length should be converted to an equivalent host bytes length prior to the addition (effectively multiply the length by 2).

My question is: is there any way that I can get the compiler to protect me from my own mistakes?

Both length types are integers. Is there way, for example, through type magic, to tell the compiler that this kind of integer can't be added to this other type of integers, for example?

Thanks!

0

There are 0 answers