简体   繁体   中英

why initializing predefined address of memory with pointer led into error

I want to know why do I get Segmentation fault (core dumped), error when I try to initialize a specific address of memory via dereferencing.

here is my code

  #include <iostream>
 
  int main()
  {
      int* manualpointer = reinterpret_cast<int*> (0x7ffc756eec74);
      *manualpointer = 52;
      //int* address = new(manualpointer) int(42);   
      return 0;
  }

I checked the link below and tried to do something like the answers but I get core dumped error.

How to initialize a pointer to a specific memory address in C++

Thanks

You can't just simply access a random address in the memory.

If you want to get a pointer to an int you can do it like this:

int a;
int *pointer = &a;

In the post you linked they just played around with memory addresses this is not the same as accessing the address.

What you are trying to do is to read a value from memory at a location that is (very certainly) not assigned to you. When doing this you usually get a Segmentation Fault.

The reason for this is quite straight forward. Assuming this would be possible then you (or some malicious code) could read and modify the data of other programs which would be very bad and a huge security risk.

The problem is that the pointer manualpointer doesn't point to any int object and so dereferencing it leads to undefined behavior . Thus when you wrote:

*manualpointer = 52; //this is undefined behavior

The above statement, dereferences manualpointer and so leads to undefined behavior.

Undefined behavior means anything 1 can happen including but not limited to the program giving your expected output. But never rely (or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash .

For example, here the program doesn't crash but here it crashes.

So the first step to make the program correct would be to remove UB(which you can do by creating an int object and making manualpointer point to it in your case). Then and only then you can start reasoning about the output of the program.


1 For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM