0
votes

Most sources I come across define segmentation faults as something along the lines of this: that they occur when a program references an undefined area of virtual memory

But since I haven't yet taken a class on Operating Systems, I usually have no idea what this means that it's an "undefined area" of virtual memory...

Also, a lot of my C programs tend to run into the segmentation fault, and unfortunately I have no idea how to fix them. Are there any good tips for how to avoid these faults, and what to do when one has been encountered when all the logic of the program seems alright?

1
Single simple answer: Learn to program. You don't need any deep understanding of any operating system, you just need to understand your programming language.Kerrek SB

1 Answers

1
votes

To put this more simply a segmentation fault is that you are reading or writing memory that you are not allowed access to because you do not own it.

A simple example is using a variable on the stack followed by some code. Say we have

char a[4];
int i=0;
for(i=0; i<1000; ++0)
     a[i]='a';
printf("Hi this line will never get printed because last line killed it\n");

So on the stack we have 4 bytes allocated for 'a', another 4 for int 'i' and now we have the code that is the function. Thing is the for statement writes a 1000 bytes into 'a' which overwrites 'i', and also kill the code following it.