Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - dereferencing a char* always gives segmentation fault

I am trying to go over the memory addresses and see different accessibility of the contiguous memory areas, which are: read-only, read&write and no accessibility. I also have a signal handler that takes care of segmentation fault so the program can continue running.


char* currentAdd;
char readBuf;

for (unsigned int i = 0; i < 0xffffffff, i+=PAGE_SIZE){
    currentAdd = (char*)i;
    jmpVar = sigsetjmp(env,1); // don't worry about this, it's handled properly

    if(jmpVar == 0){
    currentMode = MEM_RO;
    readBuf = *currentAdd; // always a segmentation fault
    
    // it can never try writing!!
    currentMode = MEM_RW;
    *currentAdd = readBuf;
    }
    else{
    ...
    }

}

my program never goes past (readBuf = *currentAdd;), which is sometimes expected but not always. Did I do something wrong?

I tried to start from i=1, to prevent what some people suggested but still it keeps giving me the segmentation fault.

question from:https://stackoverflow.com/questions/66057393/dereferencing-a-char-always-gives-segmentation-fault

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

1 Reply

0 votes
by (71.8m points)

well you start your loop at i = 0, and then give currentAdd the address of a char at the address i, so currentAdd is basically (void*)0, aka NULL, so you are deferencing NULL, and no computer really like that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...