Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

c - Why does this not give a segmentation violation fault?

#include <stdio.h>
#include <stdlib.h>

int noOfIntegers = 2;

struct stack {
  int *s;
  int top;
} st;

void push(int item) {
  st.top++;
  st.s[top] = item;
}

int main() {
  st.s = malloc (2 * (sizeof(int)));
  st.top = -1;
  push(1);
  push(2);
  push(3);
  return 0;
}

I don't understand why this is not giving a segmentation fault, as I have malloc'd space for 2 int's, and am inserting 3 into the array pointed to by the pointer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE: This question was the inspiration for my ATBG column in May 2014. Thanks for the great question!


Imagine an immense minefield, stretching to the horizon. If you drive over a mine, BOOM, your car is exploded.

In the middle of that minefield are unmined parking lots, each with four thousand numbered spaces. Each parking lot has a number. Each space has a number. Some of the lots are next to each other, some are not.

You call up the parking lot manager and request eight spaces. You are told that your spaces are in lot 100, spaces 1234 through 1241.

You drive your car to the lot, find a car in space 1243, park your car in that spot, and drive away with someone else's car.

Why didn't your car explode? Because you're not in the minefield. Haven't you broken the rules? Sure. You stole someone else's parking space. Don't do that. They'll probably be mad to not find their car there. But they're not going to blow you up.

You then drive that car to spot 4003, but the lot only has 4000 spots, so you drive to spot 4000 and then drive off the right side of the parking lot to the place that would be three spots to the right of spot 4000. That turns out to be spot #3 in parking lot 101. You park your stolen car there and steal the car that was previously in that spot.

Why didn't your car explode? Because you're not in the minefield.

You then drive to spot 8003 in lot 100, which only has 4000 spots, by going all the way through lot 100, all the way through lot 101, off the right end of it, and, uh oh, this time you head into the minefield.

Why does your car explode? Because you're in the minefield.

Now is it clear why writing to memory you don't own does not guarantee a segmentation fault? Segmentation faults mean "you are in a page of memory that isn't even a valid page". If you use a portion of a valid page that you're not supposed to, the operating system doens't know that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...