Search code examples
visual-c++access-violationargv

Visual Studio '13 (Access Violation)


When I compile and run this program via gcc(g++)/Cygwin it compiles and acts as expected.

#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
for (int arg = 1; arg <= argc; arg++)
    {
        cout << argv[arg] << endl;
    }
return 0;
}

However, when compiling with Visual Studio 13, the program compiles but I am given an access violation upon execution. What gives?

Unhandled exception at 0x000B5781 in demo.exe: 0xC0000005: Access violation reading location 0x00000000.


Solution

  • argv is a pointer to the first element of an array containing argc+1 elements. The first argc elements of this array contain pointers to first elements of null terminated strings representing the arguments given to the program by the environment (commonly the first of these strings is the name of the program, followed by the command line arguments).

    The last element of this array (the argc+1th element, which argv[argc] refers to) is a null pointer. Your code dereferences this null pointer, leading to undefined behaviour.

    The important thing to note here is that array indexing in C++ is zero based, rather than one based. This means that the first element of an array arr of length n is arr[0], and the last element is arr[n-1]. Your code appears to assume that the first element of such an array is arr[1] and that the last element is arr[n].