When doing a loop list exercise, when I do a node delete operation, the following exception occurs:
After debugging, it is found that the exception occurs when free () is releasing the space, and the exception will not occur if the
The initial code is this:
typedef struct lnode{
DataType data;
Lnode *next;
}lnode,*linklist;
int interlist (LinkList &head) {
int count,i;
Linklist p,q;
Head= (linklist) malloc (sizeof (linklist)); Linklist size is taken here.
P=head;
printf ("Please enter total number of people:");
scanf ("%d", &count);
p->data=1;
p->next=p;
For (i=2;i<=count;i++) {
Q= (linklist) malloc (sizeof (linklist));
q->data=i;
q->next=head;
p->next=q;
p=p->next;
}
Head=p;
Return Count;
}
void Gamelist (linklist &head,int count) {
Linklist p,q;
Q= (linklist) malloc (sizeof (linklist));
P=head;
printf ("%d", p->next->data);
q=p->next;
p->next=p->next->next;
Free (q);
for (int i=1;i<count;i++) {
p=p->next->next;
q=p->next;
printf ("%d", q->data);
Q= (linklist) malloc (sizeof (linklist));
p->next=p->next->next;
Free (q);
}
}
Because linklist is a pointer type, the sizeof (linklist) statistic pointer takes up memory space, that is, the number of address lines, typically 32 bits for 4 bytes, and my struct actually occupies 8 bytes, so an exception is generated, but the compiler does not report an error. If I do not free the memory, the program will execute properly until the end
But if you call free, he actually needs to release more memory than the allocated memory, potentially breaking other memory data, so the program executes to this exception
Workaround: Allocate by structure size
Head= (linklist) malloc (sizeof (Lnode));
Memory address out-of-bounds access exception