Search code examples
cmemorynodeslvalue

Checking and comparing memory addresses for variables of different type


I am trying to compare the addresses of two variables in memory:

chunk_t *old_chunk, *new_chunk;

    if(&(old_chunk + 1 + old_chunk->size) == &new_chunk) { }

Here is the prototype for chunk_t:

typedef struct chunk_tag {
    struct chunk_tag *next; /* next node in list */
    int size; /* size of node in units, not bytes */
} chunk_t;

I get compiler errors on my if statement about "lvalue required as unary '&' operand".

I thought it was because I was adding an int old_chunk->size and a chunk_t old_chunk, so I typecase old_chunk->size as a chunk_t in the if statement, and the compiler told me "conversion to non-scalar type requested"


Solution

  • You cannot take an address of a computed value. Taking an address only works for a value that is already allocated somewhere on the stack.

    Imagine saying "what is the address of the value that results from adding 1 and 2 together?" There is no address for that because it's a computed value. You need to have a variable, or a computed memory location, in order to be able to manipulate memory directly.

    From what your code looks like, you want to do your address checking without the &:

    if(old_chunk + 1 + old_chunk->size == new_chunk) { }
    

    That is because both your variables are pointers to chunk_t objects.

    Just make sure you know what you're doing. Adding 1 to old_chunk means looking sizeof(chunk_t) bytes later in memory, than where old_chunk points to. Conversely, adding old_chunk->size means looking sizeof(chunk_t) * old_chunk->size bytes later.