为什么使用malloc〜导致分段错误? [英] Why segmentation fault using malloc~?

查看:75
本文介绍了为什么使用malloc〜导致分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 dict->start=(DNODE *)malloc(sizeof(DNODE)); // error occurs here

 /* DNODE and dict defined as following:

typedef struct _DICTIONARY {
  DNODE *hash[MAX_HASH_SLOT]; // the hash table of slots, each slot points to a DNODE
  DNODE *start;               // start of double link list of DNODES terminated by NULL pointer
  DNODE *end;                 // points to the last DNODE on this list
} __DICTIONARY;

typedef struct _DICTIONARY DICTIONARY;

extern DICTIONARY *dict;


typedef struct _DNODE {
  struct _DNODE  *next;
  struct _DNODE  *prev;
  void    *data;        //  actual data points to URLNODE
  char key[KEY_LENGTH]; //  actual (URL) key 
} __DNODE;

typedef struct _DNODE DNODE;


Initialization:

  dict->start=(DNODE *)malloc(sizeof(DNODE));  //fault~? why?~
  dict->end=(DNODE *)malloc(sizeof(DNODE));
  dict->start->prev=dict->start->next=NULL;
  dict->hash[0]=dict->start;
  dict->start->data=n;
  BZERO(dict->start->key,KEY_LENGTH);



gdb:

程序收到信号SIGSEGV,分段错误.
搜寻器的initLists()中为0x00000000004016e8:c:202
202 dict-> start =(DNODE *)malloc(sizeof(DNODE));




因此,为什么在malloc行中存在段错误〜?



gdb:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004016e8 in initLists () at crawler.c:202
202 dict->start=(DNODE *)malloc(sizeof(DNODE));




So, why there is seg fault in malloc line~?

推荐答案

这已添加为在注释部分对话期间找到的解决方案.[/EDIT]

如果段错误发生在指示的行,则dict可能包含无效的地址.在其他模块中未初始化extern DICTIONARY *dict;时,可能会发生这种情况.
This has been added as the solution found during the comment section conversation.[/EDIT]

If the seg fault happens at the indicated line, dict contains probably an invalid address. This may happen when extern DICTIONARY *dict; is not initialized in the other module.


检查c常见问题解答的7.19b:
http://c-faq.com/malloc/noscale.html [
Check 7.19b of the c faq:
http://c-faq.com/malloc/noscale.html[^]

Good luck!


这篇关于为什么使用malloc〜导致分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆