Joshua Soileau
Joshua Soileau

Reputation: 3025

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"

Upvotes: 0

Views: 2693

Answers (4)

Irfy
Irfy

Reputation: 9607

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.

Upvotes: 1

Erik
Erik

Reputation: 2061

One thing is your declaration of new_chunk. It is declared as a chunk_t while old_chunk is declared as * chunk_t, a pointer to a chunk_t.

If you re-write your code as

    chunk_t * old_chunk, *new_chunk;

if((old_chunk + 1 + old_chunk->size) == new_chunk) { 
    printf("some message");
}

Then it will work. Or at least compile.

Upvotes: 0

nickolay
nickolay

Reputation: 3895

You do not need &(old_chunk + 1 + old_chunk->size). Simply old_chunk + 1 + old_chunk->size. Moreover it's better to check whether old_chunk->size >= 0 because you've declared it as int in your struct.

P.S. It's not a 'prototype'. It is definition of the structure.

Upvotes: 0

Adam Zalcman
Adam Zalcman

Reputation: 27243

The following expression

old_chunk + 1 + old_chunk->size

is not an lvalue, so you can't take its address with the & operator. This is what the compiler told you with the first error message.

The second error message tells you that you attempted invalid type conversion. It seems you did something like this:

(chunk_t) old_chunk->size

which is invalid if size is of primitive type.

Upvotes: 0

Related Questions