Reputation: 17
enum ev_type { ARRIVAL, DEP_Q0, DEP_Q1, DEP_Q2, DEP_Q3 };
struct node {
double time;
double duration;
enum ev_type event;
struct node * next;
}*evlist;
typedef struct node *nptr;
double min = 0;
void generate_new_customer(double clock, double duration)
{
nptr newev = (nptr)malloc(sizeof(nptr));
newev->duration = duration;
newev->time = min;
newev->event = ARRIVAL;
if (evlist == NULL)
{
evlist = newev;
evlist->next = NULL;
}
else
{
newev->next = evlist;
evlist = newev;
}
printf("%lf\n", evlist->time);
}
int main() {
start();
while (1) {
generate_new_customer(1, 6);
if (min > 480)
break;
min++;
}
return 0;
}
I'm trying to memory allocation using function. The function working by value of min. If min increase by 480 it stops and break. I checked it. But still debug assertion failed error happen. what should I do?
Upvotes: 1
Views: 43
Reputation: 33631
Your malloc
is incorrect. It is only allocating the size of a pointer to your struct when you need it to allocate the size of the struct itself.
Change:
nptr newev = (nptr) malloc(sizeof(nptr));
Into:
nptr newev = malloc(sizeof(struct node));
UPDATE:
I notice your function is doing a push to the front of your list. This isn't a bug, but you can simplify this a bit:
Your original code:
if (evlist == NULL) {
evlist = newev;
evlist->next = NULL;
}
else {
newev->next = evlist;
evlist = newev;
}
A slight reordering:
if (evlist == NULL) {
evlist = newev;
newev->next = NULL;
}
else {
newev->next = evlist;
evlist = newev;
}
Some further reordering:
if (evlist == NULL) {
newev->next = NULL;
evlist = newev;
}
else {
newev->next = evlist;
evlist = newev;
}
Because newev->next = NULL
is inside the if
clause where evlist
is guaranteed to be NULL
, we can change this to:
if (evlist == NULL) {
newev->next = evlist;
evlist = newev;
}
else {
newev->next = evlist;
evlist = newev;
}
Now, both the if
and the else
are identical. So, we can eliminate the redundancy and we have:
newev->next = evlist;
evlist = newev;
Upvotes: 1