好吧,根据这篇文章,我知道我正在尝试访问我无法访问的内存。我唯一能想到的就是我在哪里创建任务实例并为其赋值,但在这篇文章中,我看不出我的实现在哪里不正确。
如有任何帮助,我们将不胜感激。
#include "task.h"
struct node{
Task *task;
struct node *next;
};
void insert(struct node **head, Task *task);
void delete(struct node **head, Task *task);
void traverse(struct node *head);
#ifndef TASK_H
#define TASK_H
typedef struct task{
char *name;
int tid;
int priority;
int burst;
} Task;
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"
#include "task.h"
#include "schedulers.h"
void add(char *name, int priority, int burst){
printf("beginning of addn"); // Just a test. I never see this message print
static int x = 1;
struct node *list_head = NULL;
Task xtask = (Task) { .name = name, .tid = x, .priority = priority, .burst = burst};
insert(&list_head, &xtask);
x++;
}
void schedule(){
printf("test"); // just a place holder for now
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "task.h"
#include "list.h"
#include schedulers.h"
#define SIZE 100
int main(int argc, char ** argv[]){
FILE *in;
char *temp;
char task[SIZE];
char *name;
int priority;
int burst;
in = fopen(argv[1], "r");
if (argv[1] != NULL){
while (fgets(task, SIZE, in) != NULL){
temp = strdup(task);
name = strsep(&temp, ",");
priority = atoi(strsep(&temp, ","));
burst = atoi(strsep(&temp, ","));
add(name, priority, burst);
free(temp);
}
fclose(in);
}
else{
printf("invalidn");
return 0;
}
schedule();
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "list.h"
#include "task.h"
void insert(struct node **head, Task *newTask){
struct node *newNode = malloc(sizeof(struct node));
newNode ->task = newTask;
newNode ->next = *head;
*head = newNode;
}
void delete(struct node **head, Task *task){
struct node *temp;
struct node *prev;
temp = *head;
if (strcmp(task ->name, temp -> task -> name) == 0){
*head = (*head) -> next;
}
else {
prev = *head;
temp = temp -> next;
while (strcmp(task -> name, temp -> task -> name) != 0) {
prev = temp;
temp = temp -> next;
}
prev -> next = temp -> next;
}
}
void traverse(struct node *head){
struct node *temp;
temp = head;
while (temp != NULL){
printf("[%s] [%d] [%d]n", temp-> task -> name, temp -> task -> priority, temp -> task -> burst);
temp = temp -> next;
}
}
这里有一个非常大的问题:
void add(char *name, int priority, int burst){
printf("beginning of addn"); // Just a test. I never see this message print
static int x = 1; // <-- Since "x" is static, it will persist after you exit add()
struct node *list_head = NULL; // But both *list_head and xtask will be INVALID the moment you leave add()
Task xtask = (Task) { .name = name, .tid = x, .priority = priority, .burst = burst};
x++;
如果您试图在add()
之外使用list_head和/或xtask。。这很容易成为您违反分割规则的原因。
潜在解决方案:
在add((的外部声明它们,并将它们作为参数传入。