【问题标题】:Tree structure segmentation fault树结构分割错误
【发布时间】:2015-04-29 17:50:06
【问题描述】:

分段错误(核心转储),请帮助。我不明白我做错了什么。代码编译但我得到上面的错误。我知道代码试图访问它无法访问的内存,但我看不到它发生在哪里。

#include <stdio.h>
#include <stdlib.h>

int freq[256] = {0};

struct Node
{
  unsigned char m_ch;
  int m_freq;
  struct Node *m_ls,*m_rs;
  struct Node *m_hls,*m_hrs;
};

struct Node* createNode(int freq,char ch);
void insertTree(struct Node **root,struct Node * n);
struct Node* getBinTree(FILE *fsrc);
void inorder(struct Node *root);

int main()
{
  FILE *fsrc;
  struct Node *tree=NULL;
  fsrc = fopen("src.txt","rb");
  tree=getBinTree(fsrc);
  inorder(tree);
  return 1;
}


struct Node* createNode(int freq,char ch)
{
    struct Node *pNode=NULL;
    pNode->m_freq=freq;
    pNode->m_ch=ch;
    return pNode;
}

void insertTree(struct Node **root,struct Node *n)
{
  if(!(*root))
  {
    *root=n;
    return;
  }
  if(n->m_freq<(*root)->m_freq)
  {
    insertTree(&(*root)->m_ls,n);
  }
  else
  {
    insertTree(&(*root)->m_rs,n);
  }
}

struct Node* getBinTree(FILE *fsrc)
{
  struct Node *temp=NULL;
  struct Node **root=NULL;
  int c,i;
  while ((c = fgetc(fsrc)) != EOF)
  {
    freq[c]++;
  }
  freq[255]=1;
  fclose(fsrc);
  for(i=0;i<256;i++)
  {
    if(freq[i]>0)
    {
      temp=createNode(freq[i],i);
      insertTree(root,temp);
    }
  }
}

void inorder(struct Node *root)
{
if(root != NULL)
   {
     inorder(root->m_ls);
     printf(" %d\n",root->m_freq);
     inorder(root->m_rs);
   }
   return;
}

【问题讨论】:

  • 你试过使用你的调试器吗?

标签: c


【解决方案1】:
  struct Node *pNode=NULL;
  pNode->m_freq=freq;

其中一个原因是取消引用上面引用的代码块中的 NULL 指针。

在使用指针之前必须分配内存。像这样:

struct Node *pNode = malloc (sizeof *pNode);

【讨论】:

  • 在代码中确实没有一个malloc()calloc() 甚至realloc()
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2015-12-31
  • 2018-11-19
  • 1970-01-01
  • 2021-06-12
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多