简体   繁体   English

为什么在使用链表实现的堆栈程序中发生堆损坏? 以及如何解决?

[英]Why does heap corruption occur in my stack program implemented with linked list? And how to fix it?

I've created a C header file for a data structure course which I'm taking in school. 我为我上学的数据结构课程创建了一个C头文件。 I've only limited coding experience in C and C++. 我在C和C ++方面的编码经验有限。 It contains code which builds a stack using linked list for data storage. 它包含使用链接列表构建堆栈以存储数据的代码。 When I try to run a driver program with Visual Studio 2013 to test if the implementation works, it throws the following error: 当我尝试使用Visual Studio 2013运行驱动程序以测试实现是否可行时,它将引发以下错误:

HEAP CORRUPTION DETECTED: after Normal block (#68) at 0x006F8178. 已检测到堆损坏:在正常块(#68)之后的0x006F8178处。 CRT detected that the application wrote to memory after end of heap buffer. CRT检测到应用程序在堆缓冲区结束后写入了内存。

The code in the said header file is listed below: 所述头文件中的代码如下:

#include <stdlib.h>
#include <stdbool.h>

//type definition for a single stack data node
typedef struct node
{
    void *dataPtr; //create void pointer to user data
    struct node *link; //create pointer to next node in stack
}STACK_NODE;

//type definition for stack head structure
typedef struct stack
{
    int count; //location to hold number of entries in stack
    STACK_NODE *top; //create pointer to top of stack
}STACK;

//function to create empty stack
STACK* createStack()
{
    STACK *stack; //create a stack head node

    stack = (STACK*)malloc(sizeof(STACK));
    if (stack){
        stack->count = 0; //set stack count to zero
        stack->top = NULL; //initialize top pointer to null
    }
    return stack; //return address of node in dynamic memory
}

//function to push data onto stack
bool pushStack(STACK *stack, void *dataInPtr)
{
    STACK_NODE *newPtr;

    newPtr = (STACK_NODE*)malloc(sizeof(STACK_NODE*));
    //if out of memory
    if (!newPtr)
        return false;

    newPtr->dataPtr = dataInPtr; //assign data pointer to node
    newPtr->link = stack->top; //set link to point to node currently indicated as stack top
    stack->top = newPtr; //set top node to point to data in new node

    ++(stack->count); //add one to stack count
    return true;
}

//function to pop data off the stack and recycle node
void* popStack(STACK *stack)
{
    void *dataOutPtr;
    STACK_NODE *temp;

    //if stack is empty, return NULL
    if (stack->count == 0)
        dataOutPtr = NULL;
    else{
        temp = stack->top; //set temp to point to top node to be recycled
        dataOutPtr = stack->top->dataPtr; //set dataOutPtr to point to value currently stored in the top node
        stack->top = stack->top->link; //set top pointer to point to next node in stack
        free(temp); //delete top node
        --(stack->count);
    }
    return dataOutPtr; //return address of popped data
}

//function to retrieve data in top node
void* stackTop(STACK *stack)
{
    //if stack is empty, return NULL
    if (stack->count == 0)
        return NULL;
    //if top node contains data, return dataPtr
    else
        return stack->top->dataPtr;
}

//function to test if stack contains data
bool emptyStack(STACK *stack)
{
    return (stack->count == 0);
}

//function to delete nodes in stack
STACK* destroyStack(STACK *stack)
{
    STACK_NODE *temp;

    //if stack is not empty
    if (stack){
        //delete all nodes in stack
        while (stack->top != NULL){
            //delete data entry in top node
            free(stack->top->dataPtr);

            temp = stack->top; //set temp to point to top node to be recycled
            stack->top = stack->top->link; //set top node to point to next node
            free(temp); //destroy top node
        }
        //stack now empty, destroy stack head node
        free(stack);
    }
    return NULL;
}

The code for the driver program is listed below: 下面列出了驱动程序的代码:

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

int main()
{
    int a = 4;
    int *dataPtr, *result, *popped;

    STACK *stack1;

    //create stack
    stack1 = createStack();

    //push value in a onto stack and output value on stack top
    dataPtr = malloc(sizeof(int));
    *dataPtr = a;
    pushStack(stack1, dataPtr);
    result = (int*)stackTop(stack1);
    printf("Value in stack is: %d\n", *result);

    //pop stack and output popped value
    popped = (int*)popStack(stack1);
    printf("Value popped off is: %d\n", *popped);

    destroyStack(stack1);
    return 0;
}

TBH, when I first saw the error message I have no idea what it meant. TBH,当我第一次看到错误消息时,我不知道它是什么意思。 After doing some rudimentary research I now understand that it is caused by writing data to the heap buffer without having allocated enough memory in the first place. 经过一些初步的研究之后,我现在了解到它是由将数据写入堆缓冲区而没有首先分配足够的内存引起的。

While I'm not entirely certain, I believe the error occurs both in the popStack and destroyStack function at the line: 虽然我不确定,但我相信该行的popStack和destroyStack函数中均会发生错误:

temp = stack->top;

And it is detected and reported at the line: 并在以下行检测并报告:

free(temp);

My idea is to pass the address contained in the current top node (stack->top) to a temporary node and then call free() to release the memory in the temp node. 我的想法是将当前顶部节点(stack-> top)中包含的地址传递给临时节点,然后调用free()释放临时节点中的内存。 Since both pointers are of the same type (ie both are of STACK_NODE type), I do not understand why the assignment action would trigger a heap corruption error. 由于两个指针的类型相同(即,它们都是STACK_NODE类型的),我不明白为什么赋值操作会触发堆损坏错误。

Any help in resolving the issue will be greatly appreciated! 解决问题的任何帮助将不胜感激!

  newPtr = (STACK_NODE*)malloc(sizeof(STACK_NODE*));

Is allocating enough storage for a "STACK_NODE Pointer" - normally 4 bytes - but sizeof (STACK_NODE) is 8 bytes, so when you use newPtr you are overwriting memory. 正在为“ STACK_NODE指针”分配足够的存储空间-通常为4个字节-但sizeof(STACK_NODE)为8个字节,因此使用newPtr时会覆盖内存。

The correct form is 正确的形式是

  newPtr = (STACK_NODE*)malloc(sizeof(STACK_NODE));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM