我怎样才能在gdb中使用输入文件

时间:2011-06-21 07:41:28

标签: c debugging gdb segmentation-fault

我在编写程序时通常使用输入文件,这样我就可以避免一次又一次地输入数字的麻烦。

这是我为quicksort写的一个程序,其中一些在哪里给我分段错误

#include<stdio.h>
int partition (int *,int,int);
void quicksort (int *,int,int);
int main()
{
int i,j,a[15],choice;
int length;
printf("Entering numbers in array \n");
for(i=0;i<=14;i++)
scanf("%d",&a[i]);
printf("the sorted array is\n");
length=sizeof(a);
quicksort(a,0,length-1);
for(i=0;i<=14;i++)
 printf (" %d ",a[i]);
}
int partition(int *num,int p,int r)
{
 int x,j,i,temp;
  x=num[r];
  i=-1;
  for(j=0;j<=r-1;j++)
  {
    if(num[j]<=x)
     {
      i=i+1;
       temp=num[i];
       num[i]=num[j];
       num[j]=temp;
     }
  }
  num[i+1]=num[r];
 return i+1;
}


void quicksort (int *num,int p,int r)
{
 int q;
 if (p<r)
  {
        q=partition(num,p,r);
        quicksort(num,p,q-1);
        quicksort(num,q+1,r);
  }
}

这是我的输入文件input.txt

43 12 90 3 49 108 65 21 9 8 0 71  66 81

当我编译它时如下

cc quicksort.c
./a.out < input.txt                                          

现在我得到的输出是

Entering numbers in array 
the sorted array is
Segmentation fault

我想知道的是我经常使用gdb来调试这些问题。 是否有可能在gdb中我从同一个文件input.txt

获取输入

我使用gdb的命令集是

cc -g quicksort.c
gdb
GNU gdb (GDB) 7.1-ubuntu
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
(gdb) file a.out
(gdb) break quicksort.c:3
(gdb) run 

现在我想知道的是如何在gdb中使用输入文件,以便我不会一次又一次地输入我要输入的数组?

3 个答案:

答案 0 :(得分:4)

一如既往谷歌是您在这种“常见”用例中的朋友。

How to load program reading stdin and taking parameters in gdb?

Input redirection in gdb (MinGW)

答案 1 :(得分:3)

出于调试目的,将此行添加到程序中并注释掉第一个for循环

int a[] = {43, 12, 90, 3, 49, 108, 65, 21, 9, 8, 0, 71, 66, 81};

要获得最大的调试信息,请使用

进行编译
gcc -ggdb3 qs.c

并在gdb中以

运行它
gdb -q ./a.out 

永远不要退出你的gdb会话!如果你重新编译它,gdb会自动注意并重新加载二进制文件;通过这种方式,您将始终设置断点和您制作的其他所有内容。

由于其他已经给出了问题所在的提示,我可能会揭示一个公共宏来获取静态分配数组的大小: - )

#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))

答案 2 :(得分:0)

seg故障的原因可能是这一行。

长度=的sizeof(a)的

它的60岁。

你的r值max应该是15.整数被分配4个字节。所以你的呼叫溢出,因此错误。