01/10/2018, 09:40
Hỏi lỗi HEAP CORRUPTION DETECTED
Em có viết đoạn code về Danh sách liên kết, xóa phần tử có giá trị là 2, nhưng khi chạy thì lại báo lỗi " HEAP CORRUPTION DETECTED: after normal block(#187) at 0x0102B248. CRT detected that the application wrote to memory after end of heap buffer. Mọi người cho em ý kiến với ạ
#include <iostream>
using namespace std;
typedef struct node* Ref;
struct node
{
int key;
Ref next;
};
Ref getnode(int k)
{
Ref p;
p = (Ref)new Ref[1];
if (p == NULL)
{
cout << "khong du bo nho";
exit(0);
}
p->key = k;
p->next = NULL;
return p;
}
void addFirst(Ref &head, Ref &tail, int k)
{
Ref p = getnode(k);
if (head == NULL)
{
head = tail = p;
}
else
{
p->next = head;
head = p;
}
}
void printfList(Ref head)
{
Ref p;
if (head == NULL) cout << "Danh sahc rong";
else
{
for (p = head; p; p = p->next)
{
cout << p->key << " ";
}
}
}
void destroy(Ref &head)
{
Ref p;
while (head)
{
p = head;
head = head->next;
free(p);
}
}
void deletemid(Ref q)
{
Ref r;
r = q->next;
*q = *r;
free(r);
}
void main()
{
Ref p, head = NULL, tail = NULL,d;
int k;
while (1)
{
cout << "Nhap key, nhap 0 de thoat: ";
cin >> k;
if (k == 0) break;
addFirst(head, tail, k);
}
printfList(head);
cout << endl;
for (d = head; d; d = d->next)
{
if (d->key == 2) deletemid(d);
}
printfList(head);
system("pause");
}
Bài liên quan