gpt4 book ai didi

c - 为什么在我的双向链表中发生段错误(核心转储)?

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:04 24 4
gpt4 key购买 nike

因此,从我从其他段错误中读到的内容来看,它涉及访问您不应该访问的内存(坏内存,或者没有使用 malloc())。出于某种原因,当我创建 2 个节点时没有出现段错误,但其他任何节点都会出现段错误。如果有人可以解释一下我在这个程序中哪里出了问题,那将非常有帮助。谢谢。

    #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); '

我的头文件有这个:

    #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 循环中,在第一次迭代中 head 被设置为一个新节点。在第二次迭代中,做了一些奇怪的事情:

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

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

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

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

此处,node 设置为 NULL,因此您要写入空地址,因此是核心转储。

关于c - 为什么在我的双向链表中发生段错误(核心转储)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com