-1

I'm wondering if it's possible to get access to a variable through its memory adress in C. For example, I create a variable "aa", then I print its memory adress through printf and &aa ... Assume that its adress is 12345. Is there a way to get the variable by only using 12345 and not pointers, like that :

printf("%d", 12345);

By this way, I would like that the instruction print "aa".

Sorry if it's not clear, I will show you with the code:

int main()
{
    int aa=1; //assume its adress is 12345
    printf("%d", 12345); // I want to use 12345 as parameter to print the variable
}

Thank you very much.

huseyin39
  • 1,393
  • 12
  • 18
  • 4
    Kind of – depends why you need it. Why do you need it? – Ry- Jan 11 '18 at 10:26
  • 1
    Note that this kind of direct access typically only works in freestanding systems (usually embedded system with no operating system), or on kernel or driver code. It most likely won't work on your standard desktop application. – user694733 Jan 11 '18 at 10:42
  • 1
    Did I get it right that you want to provide the address and get back the variable identifier `aa`? This is not easy or even not possible. Variable names are processed by the compiler and linker but do not become part of the built binary code except (optionally) as debugging information. – Scheff's Cat Jan 11 '18 at 10:46
  • 1
    Though, I just remember that addresses may be searched by name in DLLs (MS Windows) or shared objects (Linux). I'm not sure whether this can be reversed. Actually, I believe this is not what you expected to hear. – Scheff's Cat Jan 11 '18 at 10:49
  • Yes you got it right, that's what I want to do. – huseyin39 Jan 11 '18 at 10:50
  • Just be clear, you want to print the *name* of the variable whose value is at a given address? If so this makes little sense (and isnt possible). You could easily have multiple variables referencing the same address, for a start, more to the point variable names aren't preserved in the compiled code, see https://stackoverflow.com/questions/14612314/how-are-variable-names-stored-in-memory-in-c – virgesmith Jan 11 '18 at 10:51
  • 1
    Your question title is misleading. You say "getting access to a variable through its address" but really what you want is to "get a variable's name from its address". – davmac Jan 11 '18 at 10:53
  • 1
    To get an impression, what we are talking about - this may help: [Object Files and Symbols](http://nickdesaulniers.github.io/blog/2016/08/13/object-files-and-symbols/). (I googled for "C binary symbol table".) – Scheff's Cat Jan 11 '18 at 10:54
  • Possible duplicate of [GDB: Getting a symbol name from a memory address](https://stackoverflow.com/questions/762628/gdb-getting-a-symbol-name-from-a-memory-address) or https://stackoverflow.com/questions/3551935/how-to-return-the-name-of-a-variable-stored-at-a-particular-memory-address-in-c or etc. You should specify what implementation you are using, as the answers depend innately on that. Did you not have any luck searching? – underscore_d Jan 11 '18 at 11:10
  • @underscore_d The question is not the same. I want to use the memory adress (12345) as a parameter in printf to print the variable. – huseyin39 Jan 11 '18 at 11:18
  • @huseyin39 You can't because C does not have introspection. – underscore_d Jan 11 '18 at 11:25
  • @underscore_d Ok thank you, so I will close the topic. May you write an answer? By this way, I could accept it as the solution. – huseyin39 Jan 11 '18 at 11:32
  • @huseyin39 I can't as the topic was closed. Fwiw, I think the marked duplicate indicates clearly why this isn't something C can do; no answer there used the same phrasing as me, but the result is the same. – underscore_d Jan 11 '18 at 11:41
  • Besides, I still can't understand this or how it can be answered. You write `//assume its adress is 12345`. How can anyone assume this? You want to print a name given its address, which isn't possible, but the basis of the question isn't sound anyway: if you *could* do it, you'd need to know the address, which you can't get by just "assuming". Maybe you think you're simplifying your question by being brief, but you're really not; it's unclear & seems like an X/Y question. Such questions should really be framed in terms of *what/why* you want to do, not *how* you currently think you might do it – underscore_d Jan 11 '18 at 21:41
  • @underscore_d Firstly I print the adress in the console, then I write it in a paper. By this way, I could get the adress... – huseyin39 Jan 13 '18 at 15:28

3 Answers3

1

Assuming the address of your variable is definitely 12345:

printf("Value at the address %d:%d", 12345, *(int*)12345);

In a more general way:

int aa = 10; // Your variable 'aa'
int* aa_ptr = &aa; // 'aa_ptr' contains the address of the variable aa.

printf("The variable 'aa' is at the address %p and contains the value: %d", aa_ptr, *aa_ptr); // '*aa_ptr' would show the value of the variable 'aa'

The address of a memory is called 'pointer' in C. Have a look to the concept of pointer in C for more explanation: first tutorial in google

Note: For your information variable are often at least 8bit aligned (and more often 32bit aligned) - the adress should be a even number. So it is unlikely you will see a variable address at an odd address like 12345, 12344 or 12346 are more likely to be valid addresses. Accessing a non-aligned address could sometime crash your program.

OlivierM
  • 2,820
  • 24
  • 41
  • 1
    Which -- caveat -- is utterly illegal *unless* you got that value (`12345`) from an earlier use of the address operator (`&`) on a `int` variable *that is still in scope*. – DevSolar Jan 11 '18 at 10:29
  • I tried it out at [**ideone**](https://ideone.com/IWlhFU) but I could've sworn it's [UB](https://stackoverflow.com/a/4105123/1505939). gcc may apply funny re-arrangements when optimizing. – Scheff's Cat Jan 11 '18 at 10:30
  • @Scheff, you should not write `size_t addr = (size_t)&a;` but `int* addr = (int*)&a;` – OlivierM Jan 11 '18 at 10:32
  • It doesn't work for me, it prints something (an integer) but not my variable. – huseyin39 Jan 11 '18 at 10:39
  • @OlivierM I read the question again (after it has been edited). I believe I resembled what huseyin39 was asking for. (Of course, I wouldn't do this in productive work.) – Scheff's Cat Jan 11 '18 at 10:39
  • I know that it works with using aa_ptr, but is-it possible to use directly its adress written as a number (12345)? – huseyin39 Jan 11 '18 at 10:45
  • 3
    You must cast to `void *` for `%p`, or get undefined behavior. Also the part about "often at least 8bit aligned" makes little sense. – unwind Jan 11 '18 at 10:50
  • @DevSolar: The right criterion is lifetime, not scope. A reference to an object is valid during the object’s lifetime. Scope is **where** in source code an identifier is visible. Lifetime is **when** in program execution an object exists. An object may exist even while executing code for which its identifier is not in scope. – Eric Postpischil Jan 11 '18 at 11:16
  • @EricPostpischil: You are correct of course. I wanted to simplify the statement as much as possible, with regards to the OP's apparent (in)experience, and probably overdid it. – DevSolar Jan 11 '18 at 14:46
1

That is what pointers are made for:

int aa = 12      ;   // defines an integer variable

int *pt = &aa;       // declare a pointer to the above variable

printf("Variable aa is at address %p\n", pt);
printf("Its value is %d\n", *pt);

In real mode programming when hardware registers are mapped at well know locations, it is even legal to store an absolute address in a pointer:

char * screenmem = 0xB800; // absolute address of the screen text buffer on a PC in REAL MODE
screenmem[0] = 'A';        // writes a A in upper left corner

But apart from:

  • taking the address of an existing object
  • using a well known address

dereferencing a pointer pointing to an arbitrary address (int * pt = 12345; *pt = 12;) invokes Undefined Behaviour.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Is it possible to do it without using pointers ? I mean by passing the adress as a parameter in printf ? – huseyin39 Jan 11 '18 at 11:08
  • @huseyin39 You will have to convert it to a pointer in order to use it. The language notion for address is pointer. – Serge Ballesta Jan 11 '18 at 11:10
  • @SergeBallesta Cannot I print it with its adress ? Must I use pointers? – huseyin39 Jan 11 '18 at 11:14
  • 1
    @huseyin39 [@OlivierM's answer](https://stackoverflow.com/a/48204828/3545273) contains a link explaining pointer concept. Using an address without using pointers is close to non sense in C language. – Serge Ballesta Jan 11 '18 at 11:19
  • @SergeBallesta Yes I have learned about pointers. But my question wasn't really about pointers but adress. Thank you annyway. :) – huseyin39 Jan 11 '18 at 11:34
  • A pointer is a variable that contains an address (mostly). – Matthias Jan 11 '18 at 12:17
0

Well, for sake of theory, yes you can do it. The question you should be asking yourself is why or when do you need it?

One way of what you expect,can be done as:

int var = 0;
int * pVar = NULL;

pVar  = &var;

printf ("The address is %p\n", (void *)&var);
printf ("The same address (via pointer variable) is %p\n", (void *)pVar );

printf ("The value at the address is %d\n", *(&var));
printf ("The value at the address (via pointer) is %d\n", *pVar );

Check at ideone

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Instead of using &var, is-it possible to write directly its adress (*12345 or something like that) ? – huseyin39 Jan 11 '18 at 10:49
  • @huseyin39 what do you mean "directly"? I'm just using a variable to hold the value, that's all. – Sourav Ghosh Jan 11 '18 at 10:53
  • 1
    @huseyin39 also, to use a hard-coded address, you need to make sure it belongs to the virtual memory space of your process, which is _hard_ to know beforehand. – Sourav Ghosh Jan 11 '18 at 10:54
  • I mean by using only its adress without pointer : printf ("The address is %p\n", *12345); something like that. – huseyin39 Jan 11 '18 at 10:56
  • That's what, how do you know that `12345` or whatever is a valid address? – Sourav Ghosh Jan 11 '18 at 10:56
  • 1
    @huseyin39 For a normal program you shouldn't do that, you cannot control the virtual memory space that the OS gives to you. However such techniques are useful for example when you are programming micro controllers and/or operating systems and you have to access a certain register at a predefined **known** address, for example the some register of the UART. – Pablo Jan 11 '18 at 10:58
  • @Sourav Ghosh Because I've printed it before with printf("%d", &aa) and remember it. – huseyin39 Jan 11 '18 at 10:58
  • 1
    @huseyin39 read about virtual memory...and try running the program multiple times. – Sourav Ghosh Jan 11 '18 at 10:59
  • 1
    @huseyin39 you might remember it, but that's meaningless. Next time you run your program, the address will most likely change and the one you "remembered" becomes invalid. Like I said in a previous comment, there is no real need for that for a normal program. – Pablo Jan 11 '18 at 11:01
  • @ Sourav Ghosh If I execute the program many times within 5 minutes, adresses won't change. – huseyin39 Jan 11 '18 at 11:02
  • @Pablo I know it is not useful, but I wanted to know if we can do it or not. – huseyin39 Jan 11 '18 at 11:03
  • 1
    @huseyin39 that's just a coincidence. Perhaps if you try hours later or after a reboot, you might see another address. But what matters is that the OS doesn't guarantee that you always get the same virtual memory space, so can't relay on this if by some coincidence the addresses are the same between consequent calls of your program. – Pablo Jan 11 '18 at 11:05
  • 1
    @huseyin39 you can shoot your foot, but will you? The answer is same. :) – Sourav Ghosh Jan 11 '18 at 11:05
  • @Pablo #Sourav Ghosh I know that after hours or rebooting the adress would change. However I have wondered this question :) .. And, I will not :P – huseyin39 Jan 11 '18 at 11:12