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

When I compile and execute this code sequentially several times, it reports the cc address as 0x0012FF5C. But when I try to print a line at this address using the second printf call in foo, it prints garbage instead of printing "Hello" ?? Why is that?? It’s wrong if I directly passed the address as an argument when I know that the address is in the address space of the application (at least until I restart my computer or start some other application that requires a lot of space and which causes my application for unloading)

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

int main()
{
    char *c[] = {"Hello","World"};
    foo(c);
}
+5
source share
10 answers

C ++, . /, .

#include <stdio.h>

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

(gcc on linux). " ";)

:

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

+12

printf char *, printf char * .

+6

, -, ,

. , . , cc - . .

, , ,

printf("%s\n",*((char**)(0x0012FF5C)));
+5

, , , . / - .

, .

+4

, (0x0012FF5C) poiter. (char *) (0x0012FF5C).

, , , , . - , , .

+3

, , . , , . , :

test.c: 'foo: test.c: 6: warning: format'% x type 'unsigned int, 2 ' char **

test.c: 7: warning: format '% s ' char *, 2 'int

test.c: 9: warning: format '% x ' unsigned int, 2 'char **

+2

,

, , , .

, . , , ( , , ).

+2

, , . . , . , . !

 #include <stdio.h>

 void foo(char *cc[])
{
    printf("%x\n",cc);
    printf("%s\n",(0x0012FF5C)); //this line will fail, there is no guarantee to that
    cc++;
    printf("%x\n",cc);
}

int main()
{
    char *c[] = {"Hello","World"};
    printf("c array location: %p",c); //print location
    foo(c);
}
+2

-, printf("%x\n",cc); cc. cc, undefined, %x. unsigned int, .

, cc ( 32- , 64- ). -.

-, cc char**, cc , c from main. %s . cc 0x0012FF5C, printf %s .

"", , - , , . .

+1

. , .

#include <stdio.h>

void foo(char cc[])
{
    int i;
    printf("%p\n",cc);
    printf("Type the address you would like to read:");
    scanf ("%x",&i);
    printf("Character value at your address: %c\n",*((char *)(i)));
}

int main()
{
    char c[] = "Hello";
    foo(c);
}

This will allow you to read the address provided on the command line. First, it will print out the base address of the character array so that you know where to look for the string.

Example:

$ ./a.out 
0xbfcaaf3a
Type the address you would like to read:bfcaaf3d
Character value at your address: l

As expected, this prints the fourth letter Hello.

0
source

All Articles