【问题标题】:My Program is crashing我的程序崩溃了
【发布时间】:2014-12-27 21:30:56
【问题描述】:

我的程序崩溃了,我不知道为什么。我正在尝试创建一个包含 10 个元素的队列。我的主要代码:

#include "queue.h"

int main(void){

Queue * queue;

queue = create_q(10);
return 0;
}

我的 queue.h 代码:

#ifndef QUEUE_H_
#define QUEUE_H_
#endif /* QUEUE_H_ */

#include <stdbool.h> /* for bool type */
#include <stdio.h> /* for standard IO support */
#include <stdlib.h> /* for malloc() and free() functions */

typedef struct patient { /* my structure */
    char name [20];
    char surname [20];
    int priority;
    struct patient * next; /* pointer to next node */
}Node;

typedef struct queue {
    Node * head;
    Node * last;
}Queue;

Queue * create_q(int size);

我的 queue.c 代码:

#include "queue.h"

Queue * create_q(int size){

Node * temp, * temp2;
Queue * new ;
int i=0,j;

temp = (Node *) malloc(sizeof(Node));
new->head = temp;
if(temp == NULL){
    printf("There is not enough memory to create the %dth Node of your queue",i);
    for (j=1; j<=i; j++){
        new->head = temp->next;
        free(temp);
    }
    return NULL;
}
if (temp != NULL){
    new->head = temp;
    for (i=1; i<size; i++){
        temp2 = (Node *) malloc(sizeof(Node));
        temp->next = temp2;
    }
    return new;
}
return 0;
}

使用 Eclipse 调试器,它似乎在 new->head = temp 处崩溃。希望有人能发现我的错误,因为我不能。

【问题讨论】:

  • 你从未为new分配空间。
  • 你是用 gcc 还是 g++ 编译这个?
  • @hyades 必须是 gcc。 g++ 可能会在一个名为 new 的变量上吐槽,因为这是一个 C++ 关键字。
  • 这一行:'int main(void){' 应该是:'int main(){'
  • 这一行:'#endif /* QUEUE_H_ */'应该在头文件的末尾,而不是头文件的第三行

标签: c crash queue


【解决方案1】:

您从未分配过新队列。你需要:

Queue *new = malloc(sizeof(Queue));

【讨论】:

  • 感谢您的帮助!
  • @user3540561 你知道如何接受答案吗?请接受这个。没错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多