karthick
karthick

Reputation: 21

pointer assignment to a variable

addr is a parameter to the function and read_value is a local variable of the function. both are of type int.

Then what does:

read_value = (* (int *) (addr))

mean?

Upvotes: 2

Views: 237

Answers (3)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43508

(int *) (addr) casts the numeric value of addr to an int * pointer. Unless special care is taken, this operation is unsafe because an arbitrary value of addr can violate the alignment requirements for int. In general, if the value of addr is not a multiple of the size of an int, it can lead to a misaligned read which can eventually result in a SIGBUS signal.

The asterisk finally fetches the int value located at that address (called dereferencing) and saves it into read_value. It is at this point where the misaligned read can happen, if the address is not sufficiently aligned. The dereference might as well cause a segmentation fault if the address happens to be restricted or protected.

I would actually declare addr to be of type uintptr_t, rather than int, since that gives more safety between the cast to int *. uintptr_t should correspond to the size and the representation of a pointer, while the int type is semantically unrelated to a pointer.

Upvotes: 5

ouah
ouah

Reputation: 145839

Take the following example:

int read_value = 0;
int address = 0x1234;

read_value = *(int *) address;

This is equivalent to:

read_value = *(int *) 0x1234;

this reads an int at address 0x1234 and stores it in read_value object. It is done by first converting the int value 0x1234 to a pointer to int and then dereferencing the pointer to access the int value pointed at.

Note that the conversion (int *) 0x1234 is implementation defined.

(C99, 6.3.2.3p5) "An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation."

And the dereference of the pointer is undefined behavior if it is an invalid pointer or if it doesn't have the correct alignment. Any use of an invalid pointer is undefined behavior. An invalid pointer is a pointer that is not null but that doesn't point to a proper object or function.

Upvotes: 1

asaelr
asaelr

Reputation: 5456

You cast addr to a pointer to int, dereference it, and put it in read_value .

If addr is really int, I think that it's undefined behavior.

Upvotes: 1

Related Questions