c - fscanf 上的段错误(核心已转储)

标签 c gcc segmentation-fault scanf

以下代码在 fscanf 的 for 循环的第二次迭代中给我一个段错误,可能是什么问题??? fflush(stdin) 在这里使用正确吗???或者还有其他原因。 该代码应该创建一个 NODE 类型的数组,每个索引包含一个链表,其中包含从 file.txt 读取的 32 个整数节点

FILE *file = fopen ("file.txt", "r");

int count =0;
int x=0;
   for ( x=0; x<=312500; x++)
     {
          while (count <=32)
        {

             fscanf (file, "%d", &temp->num);  

temp->ptr=NULL;


   newNode = (NODE *)malloc(sizeof(NODE));
   newNode->num=temp->num;
   newNode->ptr=NULL;



               if (first != 0)

           {

            last->ptr=newNode;
            last=newNode;
            count=count+1;

           }
          else

          {

             first = newNode;
             last = newNode;
             count=count+1;
           }

               fflush(stdin);

       }

          count =0;
          array[x] = (NODE*) malloc(sizeof(NODE));
          array[x]->ptr=first;


         first->ptr=0;
         first=NULL;

         last->ptr=0;
         last=NULL;

        temp->ptr = 0;  
temp=NULL;

       fflush(stdin);
        }

 fclose (file); 

最佳答案

循环的第一次迭代通过设置结束

temp=NULL;

您在内部第二次迭代开始时取消引用 NULL

fscanf (file, "%d", &temp->num);

您的代码没有显示 temp 是如何分配的,因此很难说您是应该停止将其设为 NULL 还是分配一个新实例。

关于c - fscanf 上的段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19996152/

相关文章:

c - 段错误和 realloc() : invalid next size:

c - libxml2 htmlSaveFileEnc 将 utf8 字符保存为 Г

c - 如何制作具有透明背景的 OpenGL 渲染上下文?

c - 如何在 gtk+ 中以恒定速度移动图像部件?

gcc - 构造一个 'long long'

gcc - 如何解决交叉编译中的 crt0.o 链接问题?

c++ - 在 C++ 中发生堆栈溢出时获取 SIGSEGV

c++ - 树实现给出段错误(核心转储)错误 c++ 11

c - 从函数返回的值与接收到的值不同。为什么?

linux - 我在使用mpicc进行编译时遇到技术问题