Reputation: 53
#include <stdio.h>
#include <stdlib.h>
typedef struct lis
{
int num;
struct lis * next;
} list;
void fun(list ** h, int nu) {
*h = malloc(sizeof(list)*nu);
list *p = *h;
int i=1;
list * nextx;
while(i<=nu) {
nextx = p + 1;
p->num = i;
p->next = nextx;
//printf("%d\n", nextx);
p += 1;
i++;
}
p->next = NULL;
}
int main(int argc, char const *argv[])
{
list * first = NULL;
fun(&first,10);
free(first);
return 0;
}
I'm learning lists in c
whenever this code is run it gives an malloc error
if i comment out printf("%d\n", nextx);
which shows next node it works fine.
what is happening?
Upvotes: 0
Views: 615
Reputation: 36431
In the last run of the loop, your code do:
nextx = p+1; // points one past the last array' element
p->num = nu-1; // ok
p->next = p+1; // probably not what you wanted, but not a fault per se
p += 1; // This is the cause of your problem
i++; // out of the loop...
p->next = NULL; // dereference out of array pointer!
Quit the loop one step before and then set the last element correctly:
while (i<nu) {
...
}
p->next = NULL;
p->num = nu-1;
Upvotes: 5