Hi all, what exactly is segmentation fault or access violation and exactly when does it occur?

Why does the following program work correctly :

#include <stdio.h>
#include <conio.h>

int main( )
{
    int a[5];
    a[20] = 20;
    a[-20] = 30;
    printf("%d %d", a[20], a[-20] );
    getch( );
    return 0;
}

>what exactly is segmentation fault or access violation and exactly when does it occur?
A segmentation fault is when you access memory outside of your address space and the OS politely asks you not to do that.

>Why does the following program work correctly
Undefined behavior can do anything, including work the way you expect it to. Don't rely on a single implementation to tell you what works and what doesn't. We have a standard document for that. :)

> Why does the following program work correctly
There is a big difference between "produces expected output" and "works correctly". Your program is not correct, even though it seems to pass the "works for me" test.

When run with some diagnostic software, I get

$ valgrind ./a.out
==20047== Memcheck, a memory error detector for x86-linux.
==20047== Copyright (C) 2002-2005, and GNU GPL'd, by Julian Seward et al.
==20047== Using valgrind-2.4.0, a program supervision framework for x86-linux.
==20047== Copyright (C) 2000-2005, and GNU GPL'd, by Julian Seward et al.
==20047== For more details, rerun with: -v
==20047==
==20047== Invalid write of size 4
==20047==    at 0x804838F: main (in ./a.out)
==20047==  Address 0x52BFE7E4 is just below %esp.  Possibly a bug in GCC/G++
==20047==   v 2.96 or 3.0.X.  To suppress, use: --workaround-gcc296-bugs=yes
20 30==20047==
==20047== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 13 from 1)
==20047== malloc/free: in use at exit: 0 bytes in 0 blocks.
==20047== malloc/free: 0 allocs, 0 frees, 0 bytes allocated.
==20047== For counts of detected errors, rerun with: -v
==20047== No malloc'd blocks -- no leaks are possible.

For your example, adding more code will no doubt show up all manner of weird problems, most likely close to a deadline.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.