Is it safe to cast an int to void pointer and back to int again?

前端 未结 8 1910
失恋的感觉
失恋的感觉 2020-12-06 18:18

In C and/or C++: is it safe to cast an int to void pointer and back to int again?

Based on the question \"C++: Is it safe to cast pointer to int and later back to po

8条回答
  •  猫巷女王i
    2020-12-06 19:10

    Here is an example where converting a pointer to an integer may not result in the same pointer when converting the integer to a pointer.

    Given an architecture which has 24 bit addresses and uses two 16-bit quantities to describe the location. Let one quantity be the SEGMENT and the other OFFSET. A location is designated by the notation SEGMENT:OFFSET.

    The actual 24-bit (Physical) address is calculated by:

    address = segment * 16 + offset.
    

    Using this notation, there can be more than one SEGMENT:OFFSET pair that describe the same physical address.

    When converting to an integer, a 32-bit (unsigned) quantity is used (to simplify internal calculations in the processor). The problem is how to convert the physical address into the same SEGMENT::OFFSET that was used in the creation of the physical address.

    A generic equation for converting integer to pointer is:

    offset = address & 0xFFFF; // Mask off high order bits, keep lower 16.
    segment = address >> 16;   // Shift address right 16 bits, zero fill.
    

    Although the physical address of this new segment and offset is equal to the physical address of the original SEGMENT:OFFSET, the segments and offsets are not guaranteed to be the same.

    To optimize code, there are processor instructions that use relative addressing in a segment. These instructions may get messed up when the SEGMENT value changes due to conversion from a physical address.

    In this scenario, converting from a pointer to an integer is possible. HOWEVER, converting from the integer to the pointer IS STRONGLY DISCOURAGED. Hard to debug errors could occur during run-time.

    Bonus question: Can you name the actual architecture?

提交回复
热议问题