- 论坛徽章:
- 0
|
在写一个算法,其中一部分是生成一个动态增长的链表,其参数用dis控制,就是不同数值之间的距离,其增长方式有序。然而编译这部分函数提示有段错误,用GDB调试发现完美运行。。。- #include "iostream"
- #include "cmath"
- #include "cstdlib"
- #include "cstdio"
- using namespace std;
- int a[9]={120,121,122,123,124,125,126,127,128};//测试用数组
- typedef struct absval
- {
- int dis;//dis是不同数值之间的间距
- int val;
- struct absval* next;
- }absval;
- absval* adjust(absval* head,absval* newval);
- void destroy(absval* head);
- void getknnval(int *p,int a);
- absval* adjust(absval* head,absval* newval)//根据dis大小有序地增长这个链表
- {
- if(newval->dis<=head->dis)//如果dis较小则放在这个节点前面
- {
- newval->next=head;
- return newval;
- }
- else if(head->next==NULL)//到了末尾则放在末尾
- {
- head->next=newval;
- return head;
- }
- else if(head->next!=NULL)//如果dis较大,则递归往后面放
- {
- head->next=adjust(head->next,newval);
- return head;
- }
- }
- void destroy(absval* head)//销毁这个链表,因为要多次生成调用,因此需要销毁节省空间
- {
- /* absval* pix=head;//print the whole list//打印整个链表,观测其销毁过程
- while(pix)
- {
- cout<<pix->val<<" "<<pix->next<<" ";
- pix=pix->next;
- }
- cout<<endl;*/
- if(head->next!=NULL)
- {
- absval* temp=head;
- head=head->next;
- free(temp);
- destroy(head);
- }
- else
- free(head);
- }
- void getknnval(int *p,int a)//获取数值,生成链表
- {
- absval* head=new absval;
- absval* pix;
- head->val=*p;//初始化链表头部
- head->dis=abs(*p-a);
- head->next=NULL;
- int i;
- int avval=0;
- for(i=1;i<9;i++)
- {
- pix=(absval*)malloc(sizeof(absval));//根据数组依次初始化节点
- pix->val=*(p+i);
- pix->dis=abs(*(p+i)-a);
- pix->next=NULL;
- head=adjust(head,pix);//调用函数调整这个链表,保持头部指针
- pix=head;//打印这个链表,观测链表的增长过程
- while(pix->next!=NULL)
- {
- cout<<pix->val<<" ";
- pix=pix->next;
- }
- cout<<pix->val<<endl;//打印链表尾部
- }
- pix=head;//回到头部,获取链表前5个元素的val
- for(i=0;i<5;i++)
- {
- avval+=pix->val;
- pix=pix->next;
- }
- cout<<avval<<endl;
- destroy(head);//销毁这个链表
- // return avval;//返回值,测试中没有使用这个东西
- }
- int main()
- {
- getknnval(a,124);
- return 0;
- }
复制代码 神奇的一点是,gdb下,所有的生成都是正确的,调整也是正确的,GDB下直接R的结果如下:- Starting program: /home/lhl/imp/test
- 121 120
- 122 121 120
- 123 122 121 120
- 124 123 122 121 120
- 124 125 123 122 121 120
- 124 125 123 126 122 121 120
- 124 125 123 126 122 127 121 120
- 124 125 123 126 122 127 121 128 120
- 620
复制代码 一开始我还检测了指针的值,也是正确的,没有问题。包括其销毁过程,全部正确,获取的数值也正确。
可是使用G++进行编译- lhl@ubuntu:~/imp$ ulimit -c unlimited
- lhl@ubuntu:~/imp$ g++ -g test.cpp -o test
- lhl@ubuntu:~/imp$ ./a.out
- 段错误 (核心已转储)
- lhl@ubuntu:~/imp$ gdb test core
复制代码 就会出现段错误。
调试core信息如下:- warning: core file may not match specified executable file.
- [New LWP 1667]
- warning: Can't read pathname for load map: 输入/输出错误.
- Core was generated by `./a.out'.
- Program terminated with signal 11, Segmentation fault.
- #0 0x0000000000400b60 in getknnval (p=0x7fff20daf600, a=124) at test.cpp:82
- 82 cout<<pix->val<<endl;
复制代码 调试core的运行,也是正确的,这是为什么?球找出错误。。。 |
|