Dark Templar
Dark Templar

Reputation: 1137

Segmentation faults: what they are and general tips for how to avoid them?

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?

Upvotes: 0

Views: 126

Answers (1)

Adrian Cornish
Adrian Cornish

Reputation: 23868

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.

Upvotes: 1

Related Questions