C++ 显示分段错误的代码
下面的代码显示了分段错误。错误在哪里?我只知道它在包含printf()语句的行中,但不确定原因以及如何更正。这里有人能帮我解决吗C++ 显示分段错误的代码,c++,C++,下面的代码显示了分段错误。错误在哪里?我只知道它在包含printf()语句的行中,但不确定原因以及如何更正。这里有人能帮我解决吗 #include<iostream> #include<stdio.h> #include<string> #include<readline/history.h> #include<readline/readline.h> using namespace std; int main() { usi
#include<iostream>
#include<stdio.h>
#include<string>
#include<readline/history.h>
#include<readline/readline.h>
using namespace std;
int main()
{
using_history();
string command("history");
add_history(command.c_str());
if (command == "history")
{
cout<< "hello\n";
for(int i = 0 ; i < history_length ; i++)
{
cout<<"in there\n";
HIST_ENTRY *entry = history_get(i);
cout<<"till here\n";
printf("%5d %s", i , entry->line);
}
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
使用_history();
字符串命令(“历史”);
添加_历史(command.c_str());
如果(命令==“历史”)
{
couthistory_get(offset);
的offset参数从history_base
开始。而且history_length
是历史记录中的总条目数,因此必须在循环条件中添加history_base
这意味着您应该按照以下方式重写您的循环:
for(int i = history_base ; i < history_base + history_length ; i++)
{
...
}
for(int i=history\u base;i
来自:
函数:历史记录条目*历史记录获取(整数偏移量)从
history\u base
开始,返回位置offset
处的历史记录条目(参见第2.4节历史变量)。如果没有条目,或者offset
大于历史记录长度,则返回空指针
您的代码将忽略history\u base
并从0偏移
因此,history\u get
无法成功,并返回代码未检查的空指针。尝试取消引用此指针会导致分段错误
我会这样写循环:
for (int i = 0; i < history_length; i++) {
HIST_ENTRY* entry = history_get(history_base + i);
if (entry)
printf("%5d %s", i, entry->line);
else
printf("%5d ERROR!", i);
}
for(int i=0;i行);
其他的
printf(“%5d错误!”,i);
}
注意我是如何将history\u base
偏移量添加到我的history\u get
调用中,并添加了错误检查
阅读您使用的函数的文档、执行错误检查和使用调试器是关键的编程天赋!如果在
printf
调用中出现故障,可以安全地假设条目
指针可能为空或无效。如果没有更多代码,很难判断。好吧,我将说出我在IRC上说的话。我不得不想象你没有正确地使用库,没有检查history\u get
的结果是否有错误。你应该花时间学习如何使用调试器……我们不是免费为你这么做的!我会保留0
->history\u length
循环,但添加history_base
toi
,用于调用history_get
。大大简化了一切。