C语言 为什么分割错误(核心转储)发生在我的双重链表



所以从我从其他segfault错误中读到的,它处理访问内存,你不应该访问(坏内存,或者没有使用malloc())。由于某种原因,当我创建2个节点时没有segfault错误,但其他任何情况都会出现segfault错误。如果有人能解释一下我在这个节目中哪里出错了,那将是非常有帮助的。谢谢。

    #include "header.h"
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    int main(int argc, char *argv[]) {
        int N; 
        //int oddsonly = (BITS_PER_SEG*2) - 1; 
        int NSegs;
        int numOfPrimes;
        if (argc == 2) sscanf(argv[1],"%d",&N);
            else scanf("%d",&N);
            NSegs = (int)ceil(N/(float)odds_only);
            printf("This is the number of segments made: %dn", NSegs);
        //this is how we make a doubly linked list 
        //void makelinkedlist(){
        //this is how we make a doubly linked list 
        //void makelinkedlist(){
        int i; 
        seg *node; 
        seg *current;
        //head = (seg*)malloc(sizeof(seg));
        head = NULL;
        for(i = 1; i < NSegs; i++ ) { 
            if(i == 1) {
                node = (seg*)malloc(sizeof(seg)); 
                node->prev = NULL; 
                node->next = NULL;
                head = node;
            }//if
            else{
                current = (seg*)malloc(sizeof(seg)); 
                current = head; 
                while(current->next != NULL){
                    current = current->next; 
                }//while
                node = current->next; 
                node->prev = current; 
                node->next = NULL;    
                }//else
            }//for
        printf("Done allocating %d nodesn",i); '

和我的头文件有这个:

    #ifndef EXTERN
    #define EXTERN extern
    #endif
    #define SIZE_OF_SEG      256       // 256 int per segment
    #define odds_only   16383
    #define BITS_PER_SEG     (8*SIZE_OF_SEG*sizeof(int))

    typedef struct _seg {  /* definition of new type "seg" */
        int  bits[256];
        struct _seg  *next,*prev;        
          }seg  ;
    EXTERN int NSegs;
    EXTERN seg *head;             // This variable will point to the 
                          // start of the linked list of segments !!!
    //EXTERN void clearAll( );            // Uses head to find the "bit array" (list)
    EXTERN void sieveOfE( int N );      // Uses head to find the "bit array" (list)
    EXTERN int  countPrimes( int N );   // Uses head to find the "bit array" (list)
    EXTERN void printPrimes( int N );   // Uses head to find the "bit array" (list)

在for循环中,在第一次迭代中,头被设置为一个新节点。在第二次迭代中,做了一些奇怪的事情:

current = (seg*)malloc(sizeof(seg)); 
current = head; 

现在您已经分配了一些空间,但是您已经覆盖了指向它的指针(这是内存泄漏)。之后出现错误:

while(current->next != NULL){
    current = current->next; 
}//while
node = current->next; 
node->prev = current; 

这里,node被设置为NULL,所以您正在写入空地址,因此是核心转储。

相关内容

  • 没有找到相关文章

最新更新