free()崩溃progmram:没有可用于“ntdll!RtlpNtEnumerateSubKey()的源代码

由于代码正常工作,这相对令人困惑。 我有一个使用malloc和free的链表。 他们工作得很好,直到我调用堆栈的主程序做了一些更改,没有对堆栈的调用方式进行任何更改。

#include  #include  #define null (void *)0 // LINKED LIST NODE ----------------------------------------------- // ================================================================ // Linked list node struct Node { double value; struct Node *next; }; // GLOBAL VARIABLES ----------------------------------------------- // ================================================================ // first node (global variable) struct Node *first = null; // STACK FUNCTIONS ------------------------------------------------ // ================================================================ // Push function void push(double x){ struct Node *temp = (struct Node *)malloc(sizeof(struct Node *)); temp->value = x; temp->next = first; first = temp; } // ---------------------------------------------------------------- // Pop function double pop(){ struct Node *temp; if (first == null){ return 0; } temp = first; double x = temp->value; first = first->next; free(temp); return x; } // ---------------------------------------------------------------- // Peek function double peek(){ double x = pop(); push(x); return x; } 

它位于pop函数中,其中free()位于崩溃的位置。 调用它的main函数有一个if语句,如下所示:

 // routine that gets userInput // if userInput is a number, keep adding to variable data // else if userInput is a command, copy to operator strcpy(operator, userInput); data = 0; // routine to get new userInput and data // if userInput is a command move to if statements below if(strcmp(operator, "+") == 0){ push(pop() + data); data = 0; printf(" %f\n", peek()); strcpy(operator, userInput); } 

在堆栈中执行free()期间,我得到一个“没有可用于ntdll的源!RtlpNtEnumerateSubKey()在0x77cf04e5”错误。

控制台也在输出:

警告:堆积在00931888,修改为00931894过去请求的大小为4

这条线:

 struct Node *temp = (struct Node *)malloc(sizeof(struct Node *)); 

temp分配错误的内存量。 它应该是:

 struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); // Remove the pointer 

根据经验,使用以下模式:

 type* var = malloc(sizeof(*var)); 

在你的情况下,它将是:

 struct Node *temp = malloc(sizeof(*temp)); 

另外,请阅读为什么不应该转换malloc的返回值 。