c++ - 线程 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;
}
}
解决方案
解决方案
改变
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;
被编译器成功捕获为废话并被拒绝。
推荐阅读
- python - 从 excel xlsx 到 3d 绘图的 3D 绘图测量数据
- javascript - 通过网页使用访问令牌检索 GitLab 工件文件并保存到磁盘
- javascript - 如何在不向最终用户提供 url 的情况下将数据工作室报告嵌入网站?
- python - 错误:“目标路径存在但不是目录,不会继续”pip安装问题
- java - 从当前时间戳中减去 3 周
- javascript - onClick 事件打开所有 Material-UI 对话框
- ios - 使用 NSDictionary 从 JSONObject 检索数据
- javascript - 对于正则表达式,集合中的句号 (.) 是否需要转义?
- python - 如何使用 Windows 安装 sparse_dot_topn
- c# - 为什么 MeasureString 坚持文本需要额外的高度?