Cac3a
Cac3a

Reputation: 124

Statically assign a memory address in c program

I'm building very small test program and I wanted to have the program access the same memory address every time(I know its not a good practice) to simulate some behaviors. How can I just pick a memory address to hard code in the program an try it out? Is there a way to see unused blocks of memory addresses and just block them ?

I totally understand that this might create unwanted conditions/situation.

Upvotes: 1

Views: 1347

Answers (1)

CodeTalker
CodeTalker

Reputation: 1791

You can use ampersand operator (&) to point a pointer to a specific memory address. However, your program must be able to able to legally access that address which is decided by what address range your OS has assigned to your program otherwise you will a segmentation fault.

Sample code:

void * p1 = (void *)0x28ff44;

Or if you want it as a char pointer:

char * p2 = (char *)0x28ff44;

PS

You can find out the address allocated to your program and take one of the addresses from it into your program. For a single run, your program will access the same memory location but for another run, it will be different one assigned to your process but same for that run.

You can refer here to check how you can read memory address assigned to your process. You can take input at runtime to provide your process id to get the filepath.

Work around

Since you mentioned it is small test program, you can also save yourself your efforts by just disabling randomization of memory addresses by disabling ASLR for your testing your program, you just disable ASLR in linux using

echo 0 > /proc/sys/kernel/randomize_va_space

and then run your program, declare and initialize a variable, print its address and then hardcode that address in your program. Bingo!! Everytime that address will be used untill you enable ASLR again.

However it is not secure to turn off ASLR and after testing you should enable ASLR again by

echo 1 > /proc/sys/kernel/randomize_va_space

Upvotes: 1

Related Questions