【发布时间】:2015-03-23 14:47:22
【问题描述】:
我在以下代码块之一中遇到分段错误,但我怀疑是这个,xbits.c:
#include <stdio.h>
#include <math.h>
void itox(int n, char hexstring[]);
int xtoi(char hexstring[]);
void itox(int n, char hexstring[]) {
hexstring[2*sizeof(n) + 1];
int ratio, remainder;
int i = 0;
while(ratio != 0)
{
ratio = n / 16;
remainder = n % 16;
if (remainder == 10){
hexstring[i] = 'A';
i++;
}
else if (remainder == 11){
hexstring[i] = 'B';
i++;
}
else if (remainder == 12){
hexstring[i] = 'C';
i++;
}
else if (remainder == 13){
hexstring[i] = 'D';
i++;
}
else if (remainder == 14){
hexstring[i] = 'E';
i++;
}
else if (remainder == 15){
hexstring[i] = 'F';
i++;
}
else
hexstring[i] = remainder;
}
i++;
hexstring[i] = '\0';
}
int xtoi(char hexstring[]) {
int i, integer;
int length = getLength(hexstring);
for (i = length-2 ; i >= 0 ; i--)
{
integer += (int) pow((float) hexstring[i] , (float) i);
}
return integer;
}
int getLength (char line[])
{
int i;
i=0;
while (line[i])
++i;
return i;
}
以上依赖于一个我还没有调试过的主方法showxbits.c,但是当我使用测试主方法时出现分段错误错误,当我使用gdb时出现以下错误。
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007ad in itox ()
这让我相信问题出在上述 .c 文件中的 itox 中。该程序应该将 int 转换为 hex 并将 hex 转换回 int。
【问题讨论】:
-
你怀疑?调试器会告诉你 exact 行。
-
gdb 告诉我错误出现在 itox 中,但不是出现错误的行。 (gdb) 运行启动程序:/home/gkendall/showxbits 程序收到信号 SIGSEGV,分段错误。 0x00000000004007ad in itox()
-
然后使用
-g编译以包含调试信息。添加-Wall以查看一些非常有用的消息,例如关于未初始化的变量。 -
阅读这篇文章也可以帮助您帮助自己:ericlippert.com/2014/03/05/how-to-debug-small-programs
-
在第一次迭代中,
while(ratio != 0)使用ratio未初始化。
标签: c segmentation-fault gdb