Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we use direct addressing in c or c++ code?

Tags:

c++

c

pointers

When I compile and execute this code consecutively for a couple of times, it reports the address of cc as 0x0012FF5C. But when I try to print out the string at that address using the second call to printf in foo, it prints garbage instead of printing out "Hello"?? Why so?? What's wrong if I directly paas the address as an argument when I know that the address lies within the address space of the application (atleast until I don't reboot my PC, or start some other application which requires a lot of space and which causes my application to be paged out)??

void foo(char *cc[])
{
    printf("%x\n",cc);
    printf("%s\n",(char *)(0x0012FF5C));
}

int main()
{
    char *c[] = {"Hello","World"};
    foo(c);
}
like image 932
user1232138 Avatar asked Apr 26 '12 12:04

user1232138


People also ask

Why is indirect addressing used?

Indirect addressing may be used for code or data. It can make implementation of pointers, references, or handles much easier, and can also make it easier to call subroutines which are not otherwise addressable. Indirect addressing does carry a performance penalty due to the extra memory access involved.

What is direct addressing?

Direct addressing is a scheme in which the address specifies which memory word or register contains the operand.

What is the difference between direct and indirect addressing?

The direct addressing mode contains the concerned operand in the instruction code's address field. In the case of an indirect addressing mode, the operand's address stays in the address field of any instruction. It requires no memory references for accessing the data.

What is direct addressing C++?

This is a C++ program to implement Direct Addressing Tables. Direct Addressing Tables are used when each element has a key drawn from a universal set S = {0, 1, . . . ,n − 1} where n isn't too large and each key is unique. It facilitates fast insertion, searching and deletion operations.


1 Answers

Because there is nothing in the C or C++ standard to guarantee that. Those addresses may be predictable depending your compiler/OS, but don't count on it.

#include <stdio.h>

int main(void) {
    char s[] = "okay";
    printf("%p", (void*)s);
    return 0;
}  

I get a different address every time (gcc on linux). Don't use "address literals" ;)

Process address space on modern OS's is randomized for security on each execution:

http://en.wikipedia.org/wiki/Address_space_layout_randomization

like image 134
CodeClown42 Avatar answered Nov 15 '22 08:11

CodeClown42