C 为什么在我的双链接列表中会出现分段错误(核心转储)?

C 为什么在我的双链接列表中会出现分段错误(核心转储)?,c,linked-list,segmentation-fault,dump,C,Linked List,Segmentation Fault,Dump,所以从我从其他seg错误中读到的内容来看,它处理的是访问不应该访问的内存(坏内存,或者没有使用malloc()。由于某些原因,当我创建2个节点时,没有seg fault错误,但任何其他节点都会得到seg fault错误。如果有人能解释一下我在这个项目中的错误,那将是非常有帮助的。谢谢 #include "header.h" #include <stdlib.h> #include <stdio.h> #include <math.h&

所以从我从其他seg错误中读到的内容来看,它处理的是访问不应该访问的内存(坏内存,或者没有使用malloc()。由于某些原因,当我创建2个节点时,没有seg fault错误,但任何其他节点都会得到seg fault错误。如果有人能解释一下我在这个项目中的错误,那将是非常有帮助的。谢谢

    #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: %d\n", 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 nodes\n",i); '

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

current = (seg*)malloc(sizeof(seg)); 
current = head; 
现在您已经分配了一些空间,但是您已经覆盖了指向它的指针(这是内存泄漏)。后来出了问题:

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

node = current->next; 
node->prev = current; 

在这里,节点被设置为NULL,因此您正在写入NULL地址,因此核心转储。

请。不要使用
sscanf()
为此,请使用
strtol()
将非
NULL
参数传递到
endptr
以检查值是否为数字。并检查
scanf()
的返回值,否则程序可能会调用未定义的行为。不要随意将
ceil()
强制转换为
int
阅读它返回
float
的原因。检查
malloc()
返回的指针是否为
NULL
。谢谢!所以current->next没有指向任何东西,因为我没有对节点进行malloc()。我添加了current->next=(seg*)malloc(sizeof(seg));我不会再犯错误了,这是你暗示的还是随机的运气。谢谢你的时间和帮助。
while(current->next != NULL){
    current = current->next; 
}//while

node = current->next; 
node->prev = current;