访问冲突写入位置 0xCDCDCDCD [英] Access Violation writing location 0xCDCDCDCD

查看:29
本文介绍了访问冲突写入位置 0xCDCDCDCD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个结构students"和另一个结构stack"来创建一个小的链表,该结构包含学生结构和指向下一个元素的指针.

I am trying to make a small linked list using one structure "students" and another sturcture "stack", which holds the student structure and the pointer to the next element.

然而,我不断收到内存访问错误.我仔细检查以确保所有指针都已初始化(只有一个指针,Stacktop,初始化为 NULL)

However i constantly keep getting a memmory access error. I double checked to make sure all pointers are initialized (only one pointer, Stacktop, initialized to NULL)

这里是结构定义:

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

using namespace std;

struct students
{
   int matnr;
   string name;
};

struct stack
{
   students stud;
   stack *next;
};

typedef struct stack Stack;
typedef Stack *ptrStack;

void push(students s);
students pop();
int isEmpty();
void printStack(students stud);

这是推送功能(它不断使程序崩溃)

Here is the push function (which keeps crashing the programm)

#include "stack.h"

ptrStack Stacktop = NULL;

void push(students s)
{
    ptrStack stack = (ptrStack)malloc(sizeof(Stack));

    if (stack == NULL)
    {
        cout << "!!FIN!!" << endl;
        return;
    }

    stack->stud = s;
    stack->next = Stacktop;
    Stacktop = stack;

    return; 
}

这里是主要的:

#include "stack.h"

students readStuds()
{
    students s;

    cout << "Enter Student name: " << endl;
    cin >> s.name;
    cout << "Enter Matr Nr: " << endl;
    cin >> s.matnr;

    return s;
}

int main()
{

char c;

do {
        push(readStuds());

        cout << "Continue Entering Students? " << endl;
        cin >> c;
        cout << "----------------------" << endl;
        cout << "----------------------" << endl;
} while (c != 'q');

cout << " POPPING STACK " << endl;
cout << " ............. " << endl;

while (isEmpty())
{
    printStack(pop());
}

}

推荐答案

这个:

ptrStack stack = (ptrStack)malloc(sizeof(Stack));

分配足够的内存来保存 struct stack aka Stack,但是 malloc() 不做任何事情来初始化返回的内存.因此,特别是,新 stack 中的 string 包含随机垃圾,然后由您的 cin >> 解释.s.name,并假定为有效的 string,但它不是,因此代码失败.

allocates enough memory to hold a struct stack a.k.a Stack, but malloc() does not do anything to initialize the memory that is returned. So, in particular, the string inside your new stack contains random garbage, which will then be interpreted by your cin >> s.name, and assumed to be a valid string, which it isn't, so the code fails.

解决方案 - 改用 ptrStack stack = new Stack.更好的是,编写适当的构造函数/析构函数、复制构造函数、赋值运算符等...

Solution - use ptrStack stack = new Stack instead. Even better, write proper constructors/destructors, copy constructors, assignment operators, etc...

这篇关于访问冲突写入位置 0xCDCDCDCD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆