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

时间:2015-06-04 22:03:42

标签: c

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

#include <stdio.h>
#include <stdlib.h>

#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()期间,我得到的是#34; ntdll!RtlpNtEnumerateSubKey()0x77cf04e5&#34;错误。

控制台也在输出:

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

1 个答案:

答案 0 :(得分:0)

该行:

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));

另请阅读why you should not cast the return value of malloc