Based on the C language in the middle of the error problem

  • 2020-04-01 23:37:11
  • OfStack

I often encounter segment errors when writing c under Linux.
So let's take a closer look.
 
Violations errors or paragraphs (segmentation violation)
See Expert C Programming(Peter Van Der Linden) pg. 156
Explaining that the segment error is due to an exception in the memory management unit (MMU),
This exception is usually caused by dereferencing an uninitialized or illegal pointer.

The pointer is referring to an address that is not in your address space.
Examples from the book


int *p = 0;  
*p = 17;  

So obviously address 0 is not the address space that your program is in
And when I tried it, it was almost always a segment error to give an address
This is also normal, it is difficult to know the address space assigned to you by the system before running it.
 
So I tested it this way

int *p = 0;  
 int a = 7;  

 printf("a addr is %dn",&a);  
 scanf("%ld",&p);  

 printf("%d",*p);

Because the address of variable a must be in the address space that the system assigns to your program
So you assign p to the address of a
Or an integer multiple of 4 up or down in a decimal is fine
No segment errors were tested

Analyze the reasons
In Linux, when you malloc a segment of memory, you just get the virtual address of that segment of memory, and that virtual address doesn't actually map to the physical address.
Only when you use this memory will the system request that the corresponding page table be mapped to the corresponding physical address.
And *p points directly at random to a virtual address   This virtual address has no actual physical address to map to.
At this point, the derejection will throw an exception at the MMU, and returning to Linux will report a segment error to the user.
And if you define an int this should be a stack address that the kernel has mapped to an actual physical page
You move the address up and down slightly on this basis. The corresponding physical address should be mapped to it.
Naturally there is no problem.

All of the above is my personal understanding. There may be some shortcomings.
Welcome to exchange advice!


Related articles: