Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception thrown at 0x50E6F1C0 (ucrtbased.dll) in CandidateVotes.exe: 0xC0000005: Access violation reading location 0x00000000

Tags:

c++

I'm getting this notification when I try to run my program.

Exception thrown at 0x50E6F1C0 (ucrtbased.dll) in CandidateVotes.exe: 0xC0000005: Access violation reading location 0x00000000.

Here's my code:

Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The program should then output each candidate's name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election.

void main()

{
    string name[5] = { 0 };
    int votes[5] = { 0 };
    int total = 0;

    for (int i = 0; i < 5; i++)
    {
        cout << "What is the name of Candidate number " << i + 1 << "?" << endl;
        cin >> name[i];

        cout << "How many votes did " << name[i] << " receive?" << endl;
        cin >> votes[i];

        total += votes[i];

        cout << total << endl;
    }

    system("pause");

}
like image 525
Foonbee Avatar asked Oct 04 '17 14:10

Foonbee


2 Answers

The problem occurs here:

string name[5] = { 0 };

This attempts to construct an array of 5 std::string objects, with the first string initialized with 0.

As it happens, this calls the following constructor:

basic_string(const char * const _Ptr)

And then, as soon as the null pointer is dereferenced, the access violation error is reported.

Passing a null char* pointer to a std::string constructor is undefined behavior.


There is no need to provide an initializer for the array, as the std::string default constructor will initialize each element properly:

string name[5];

If you want to indicate that the initialization was considered then the following syntax would be ok:

string name[5] = {};

or

string name[5]{};

Finally, it is always a good idea to enable as many reasonable warnings as possible. On MSVC with Level4 (/W4), I get the following warning:

warning C6387: 'Param(1)' could be '0': this does not adhere to the specification for the function 'std::basic_string<char,std::char_traits<char>,std::allocator<char> >::{ctor}'.

Taking note of this could avoid some confusion later on.

like image 147
wally Avatar answered Sep 29 '22 07:09

wally


You are trying to construct std::string with null. Remove 0 from the initialisation list for name or remove the initialisation list completely.

string name[5];
like image 21
bgfvdu3w Avatar answered Sep 29 '22 05:09

bgfvdu3w