动态分配内存时的访问冲突(Access violation when dynamically allocating memory)

编程入门 行业动态 更新时间:2024-10-26 06:35:49
动态分配内存时的访问冲突(Access violation when dynamically allocating memory)

我正在为学校的项目编写一个程序,要求我们根据从文件中读取的数据(在本例中为字符串)创建Binary Search Tree 。 当输入重复的字符串时,树应该通过递增整数值来允许重复。

TreeNode是一个结构如下:

struct TreeNode { string word; int count; TreeNode * left; TreeNode * right; };

我遇到的问题是当我尝试调用插入函数时程序崩溃。 我运行调试器,我收到以下错误:

在Proj12.2.exe中0x00E2A87C抛出异常:0xC0000005:访问冲突读取位置0x00000014。

导致此错误的原因是什么? 以下是相关代码的其余部分:

TreeNode * Root = new TreeNode; Root->right = NULL; void insert(TreeNode *& root, string item) { //insert function, called by Root->right,temp if (root->word == item) { root->count++; return; } if (root == NULL && root->word != item) { root = new TreeNode; root->left = NULL; root->right = NULL; root->word = item; root->count = 1; return; } if (item < root->word) { insert(root->left, item); } if (item > root->word) { insert(root->right, item); } }

I am writing a program for a project at school that requires us to create a Binary Search Tree based on data read from a file (in this case strings). The tree should allow for duplicates by incrementing an integer value when a duplicate string is entered.

The TreeNode is a struct as follows:

struct TreeNode { string word; int count; TreeNode * left; TreeNode * right; };

The problem I am having is when I try to call the insert function the program crashes. I run the debugger and I get the following error:

Exception thrown at 0x00E2A87C in Proj12.2.exe: 0xC0000005: Access violation reading location 0x00000014.

What is causing this error? Here is the rest of the relevant code:

TreeNode * Root = new TreeNode; Root->right = NULL; void insert(TreeNode *& root, string item) { //insert function, called by Root->right,temp if (root->word == item) { root->count++; return; } if (root == NULL && root->word != item) { root = new TreeNode; root->left = NULL; root->right = NULL; root->word = item; root->count = 1; return; } if (item < root->word) { insert(root->left, item); } if (item > root->word) { insert(root->right, item); } }

最满意答案

if(root == NULL)应该是您在尝试使用 - >运算符访问任何数据成员之前执行的第一次检查。 condition:if(root-> word == item)condition:if(root == NULL && root-> word!= item)

您的root为NULL,然后您尝试访问导致崩溃的root-> word。 您正尝试使用无效指针访问数据成员。

if(root == NULL) should be the first check you perform before trying to access any data members using the -> operator. condition: if(root->word == item) condition: if (root == NULL && root->word != item)

Your root is NULL and then you are trying to access root->word which is causing the crash. You are trying to access data member using an invalid pointer.

更多推荐

本文发布于:2023-08-07 05:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462586.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:冲突   内存   动态分配   Access   memory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!