Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: invalid type argument of unary ‘*’ (have ‘long int’)

Tags:

c

pointers

This is a small program written by me to print the value stored at memory location (0x7fffdf222fec).I am getting error as 4:20: error: invalid type argument of unary ‘*’ (have ‘long int’ printf("\n %p ",*(0x7fffdf222fec));

I am using gcc compiler in ubuntu 16.04.My ram is 4 GB. Cannot i access values at this location using this way?

#include<stdio.h>
void main(){
    printf("\n  %p   ",*(0x7ffeae3b3674));
}

The expected result is the junk value stored at the address

I wrote a program like this and got the address of a as

#include<stdio.h>
void main(){
    int a;
    printf("%p",&a);
}

0x7ffeae3b3674

Then i applied the above address to t he first program.

like image 671
sobha Avatar asked Jan 26 '23 06:01

sobha


1 Answers

Change *(0x7fffdf222fec) to *(int*)0x7fffdf222fec.

0x7fffdf222fec is a constant with type long int. You cannot dereference non-pointer types, so you need to cast it to a pointer first. Which pointer you choose depends on how you want to interpret the data at that address. I chose int* for this example, but you can choose any pointer type except void*.

Note though that chances are that this will segfault. Don't do this unless you're sure that you have access to that location.

To clarify:

Cannot i access values at this location using this way?

Well, it depends on what you mean. It is the right way to read that specific location. The problem is that you might not have access to it.

The access control is in general out of your reach. A segmentation fault is basically the operating systems way of telling you that you did something naughty.

You can read more about segmentation faults here

Gaining access to an arbitrary part of the memory is pretty complex and also heavily system dependent. It's not done in the same way on a Unix machine as it is on a Windows machine.

Also remember that most modern operating systems utilizes virtual memory, so the address you're trying to read is not the physical address. The OS maps a virtual address to a physical address. Read more here

I wrote a program like this and got the address of a as

You're not guaranteed to get the same address each time you run the program. If you have declared a variable, you obviously have access to it. Try to run the program several times. Chances are high that you will get a different address each time.

Unless you have very specific needs, such as coding drivers, kernels or embedded systems, you should never worry about absolute addresses.

like image 167
klutt Avatar answered Feb 15 '23 21:02

klutt