j_lo2004
j_lo2004

Reputation: 21

Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) error in xcode

I'm an amateur programmer learning how to use c++ in xcode, and I've been trying to create a program where you answer asked questions, and the questions are different depending on your answers. The thing is, I keep getting the error: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0), and I have no idea what caused it. Here's my code currently:

#include <iostream>
#include <string>
using namespace std;
int main() {


    string name;
    cout << "what is your name ";
    getline (std::cin, name);
    string yes;
    cout << "ok, " << name << ", do you want to play a game?  ";
    getline (std::cin, yes);
    cout << "\nno " << std::endl;

    string input =0;
    cin >> input;
    string Yes = "yes";
    string No = "no";

    if (input == No)
    {
        cout << "ok, sorry" << endl;
    }
    else if (input == Yes)
    {
        cout << " a question" << endl;
    }
}

Upvotes: 2

Views: 6229

Answers (1)

user4581301
user4581301

Reputation: 33932

Solution

Change

string input =0;

to

string input;

And input will be constructed as an empty string.

So What Just Happened?

string input =0;

invokes a string constructor with the number 0. There is no direct constructor for string that takes an integer, but

string(const CharT* s, 
       const Allocator& alloc = Allocator() );

is close enough. Integer 0 is treated as a pointer to 0, NULL, and the poor string tries to construct itself from a null pointer. This means it's going to copy characters from NULL until it finds a string-terminating null character.

Fortunately that march to nowhere is halted quickly because the first few thousand bytes of memory are almost always tagged as a no-go zone, crashing the program the instant you try to access anywhere in the zone. This makes a null pointer bug almost instantly detectable and very easy to debug. Just wait for the program to crash and then walk back up the stack to see where the null pointer came from. It might take a bit more work to find out why it was null, but if programming was easy, everybody'd be doing it.

To test the hypothesis, I've thrown together a simple class to simulate the behaviour without crashing

#include <iostream>

class test
{
public:
    test (const char * valp)
    {
        std::cout << "in char * constructor. Got: " << (void*) valp;
    }
};
int main() {
    test input =0;
}

The output is

in char * constructor. Got: 0

Showing that 0 was indeed enough to convince test to accept 0 as a char pointer.

Note that this is just a special case around zero, most likely to support the good ol' #define NULL 0 macro and

test input =1;

is successfully caught by the compiler as nonsense and rejected.

Upvotes: 3

Related Questions