Reputation: 119
I want to store some value into specific memory address like a pointer does. my code:
int i = 10;
printf("i address %p\n", &i);
// i address, for example, 0x7fff5d9b5478. It may differ from your system.
//I use this address and assign to pointer p.
p = (int *)0x7fff5d06d478;
// print out p address, make sure it is the i's address.
printf( "p %p\n", p);
// I assign value 0x100 to pointer p.
*p = 0x100;
// it thows me segmentation fault.
printf( "p %p\n", p);
return 0;
I want to know why the last step it throws me segmentation fault. Is it because I want to access some illegal memory? if so, where is it? how to fix it.
Upvotes: 1
Views: 4416
Reputation: 182629
I want to know why the last step it throws me segmentation fault.
Since I see you hardcode the address I assume you do this:
i
)This is wrong: the address only has a meaning in the original address space. Using it in the second process makes little sense and is most definitely not defined.
A simple way to experiment with this would be to print the address and then read it (or a slightly larger/smaller value) back in from the user, in the same process. One could argue that this is just an inefficient alternative to using pointer arithmetic, and they would be right. It would however be an effective way to establish that addresses are in no way magical, just numbers.
Another way to experiment with this would be to disable address space randomization. This will make objects consistently have the same addresses which you will be able to easily predict.
Upvotes: 1
Reputation: 163
This address space does not belong to this process
Blockquote The term "segmentation" has various uses in computing; in the context of "segmentation fault", a term used since the 1950s, it refers to the address space of a program.[citation needed] With memory protection, only the program's address space is readable, and of this, only the stack and the read-write portion of the data segment of a program are writable, while read-only data and the code segment are not writable. Thus attempting to read outside of the program's address space, or writing to a read-only segment of the address space, results in a segmentation fault, hence the name. Blockquote
http://en.wikipedia.org/wiki/Segmentation_fault
Upvotes: 1