【发布时间】:2019-10-31 12:16:56
【问题描述】:
释放仅包含 int 和 next 的链表时出现内存错误。
我已经尝试了代码开头显示的以下功能。
该程序接收链表中的节点数和每个节点的值。接下来,程序询问列表的旋转次数 (k),并将列表向左旋转 k 个数字。该函数运行良好,直到释放分配的内存。 错误发生在 free(temp) 行“Debug error HEAP CORRUPTION DETECTED”中。
#include <stdio.h>
#include <stdlib.h>
typedef struct IntNode
{
int val;
struct IntNode* next;
} IntNode;
void printList(IntNode* list);
void freeList(IntNode* head);
IntNode* createNode(int val);
void moveKPlaces(IntNode** list, int k);
int numNodes = 0;
int main(void)
{
IntNode* list = NULL;
IntNode* curr = list;
IntNode* newNode = NULL;
int i = 0, num = 0, k = 0;
printf("How many nodes in list? ");
scanf("%d", &numNodes);
getchar();
for (i = 0; i < numNodes; i++)
{
printf("Enter number: ");
scanf("%d", &num);
getchar();
if (i == 0)//head of the list
{
newNode = createNode(num);
list = newNode;
curr = list;
}
else
{
while (curr->next != NULL)
{
curr = curr->next;
}
newNode = createNode(num);
curr->next = newNode;
newNode->next = NULL;
}
}
printf("Choose a number k, and the list will be rotated k places to the left: ");
scanf("%d", &k);
getchar();
printf("The rotated list:\n");
moveKPlaces(&list, k);
printList(list);
freeList(list);
getchar();
return 0;
}
/*
This function recieves a pointer to a pointer to the head of a list and
a number (k) and rotate the list k places to the left.
input:
a pointer to a pointer to the head of a list and
a number (k)
output:
none
*/
void moveKPlaces(IntNode** list, int k)
{
IntNode* curr = *list;
IntNode* last = NULL;
IntNode* head = *list;
int placeNode = 0;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = head;//turn it to a circular list
while (placeNode < k)
{
curr = curr->next;
placeNode++;
}
*list = curr->next;// the k node will be the head
curr->next = NULL;// the one before will be the last
}
//************************************
// Method: printList
// Returns: void
// Description: prints list recursively
// Parameter: IntNode * list
//************************************
void printList(IntNode* list)
{
if (list)
{
printf("%d ", list->val);
printList(list->next);
}
else
{
printf("\n");
}
}
void freeList(IntNode* head)
{
IntNode* temp = NULL;
IntNode* curr = head;
while (curr)
{
temp = curr;
curr = (curr)->next;
free(temp);
}
head = NULL;
}
IntNode* createNode(int val)
{
IntNode* newNode = (IntNode*)malloc(sizeof(newNode));//will alocate every person node dinamically
newNode->val = val;
// insert all details
newNode->next = NULL;
return newNode;
}
预计免费且没有任何错误 “检测到调试错误 HEAP CORRUPTION”。
【问题讨论】:
-
当您输入值时,getchar 是无用的,并且每次都搜索列表的末尾很昂贵。检查 scanf 在所有情况下都返回 1 以了解是否输入了有效数字。
printf("\n");仅输出 \n 的成本很高。为什么head = NULL;在 freeList 的末尾?看看valgrind,对你有很大帮助
标签: c