首页 > 解决方案 > 线程 1:xcode 中的 EXC_BAD_ACCESS (code=1, address=0x0) 错误

问题描述

我是一名业余程序员,正在学习如何在 xcode 中使用 c++,并且我一直在尝试创建一个程序,您可以在其中回答所提出的问题,并且问题会根据您的答案而有所不同。问题是,我不断收到错误消息:线程 1:EXC_BAD_ACCESS (code=1, address=0x0),我不知道是什么原因造成的。这是我目前的代码:

#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;
    }
}

标签: c++xcode

解决方案


解决方案

改变

string input =0;

string input;

并且input将被构造为一个空字符串。

那么刚刚发生了什么?

string input =0;

调用string编号为 0 的构造函数。对于采用整数的字符串没有直接构造函数,但是

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

足够接近。整数 0 被视为指向 0 的指针NULL,而穷人string试图从空指针构造自己。这意味着它将复制字符,NULL直到找到以字符串结尾的空字符。

幸运的是,无处可去的进程很快就停止了,因为前几千字节的内存几乎总是被标记为禁止区域,当您尝试访问该区域中的任何位置时,程序就会崩溃。这使得空指针错误几乎可以立即检测到并且非常容易调试。只需等待程序崩溃,然后返回堆栈查看空指针的来源。找出为什么它为空可能需要更多的工作,但如果编程很容易,每个人都会这样做。

为了检验这个假设,我拼凑了一个简单的类来模拟行为而不会崩溃

#include <iostream>

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

输出是

在 char * 构造函数中。获得:0

表明 0 确实足以说服test接受 0 作为char指针。

请注意,这只是零附近的一个特例,最有可能支持 good ol'#define NULL 0宏和

test input =1;

被编译器成功捕获为废话并被拒绝。


推荐阅读