简体   繁体   English

如何正确释放动态 memory

[英]How do i release dynamic memory properly

im taking an oop course in c++ and was working on this assignment.我正在参加 c++ 的 oop 课程,并且正在完成这项任务。

Class of a number represented as an array of integers,boolean expression as a sign of the number(true is +,false -). Class 将一个数表示为整数数组,boolean 表达式作为数的符号(true 为 +,false -)。 The program runs ok and does all what it needs,my problem is it is crashing on the end of the main when it gets to the return line.i found that by removing the destructor thst i have build the program runs ok,i tried to see where i am accessing memory that isnt allocated and couldnt find a problem with my code.该程序运行正常并完成了它需要的所有操作,我的问题是当它到达返回线时它在 main 的末尾崩溃。我发现通过删除我构建的析构函数,程序运行正常,我试图看看我在哪里访问没有分配的 memory 并且找不到我的代码问题。 The error that pops is heap error when i get to the last line in the Driver.cpp(main func)当我到达 Driver.cpp(main func) 的最后一行时,弹出的错误是堆错误

thank you in ad谢谢你的广告

https://gist.github.com/michaelkosoy/630ff729aaa0a00a56786f3d8b84158f https://gist.github.com/michaelkosoy/630ff729aaa0a00a56786f3d8b84158f

So you have an error in your copy constructor.因此,您的复制构造函数中有错误。 After executing the copy constructor two numbers will share the same digits array.执行复制构造函数后,两个数字将共享相同的数字数组。 This means when the destructors are called the same memory will get deleted twice, resulting in a heap error.这意味着当析构函数被调用时,相同的 memory 将被删除两次,从而导致堆错误。

You should write your code to ensure that every Number get it's own digit array in all circumstances.您应该编写代码以确保每个Number在所有情况下都获得自己的数字数组。

You are also lacking an assignment operator, which means the same issue is going to happen if you assign one number to another.您还缺少一个赋值运算符,这意味着如果您将一个数字分配给另一个数字,也会发生同样的问题。

Some further reading on this very important topic.关于这个非常重要的主题的一些进一步阅读

Note that the public function setArr that allows anyone to set the digit array of a Number is fundamentally wrong, because it means you cannot know where the array of a particular number has come from, and therefore you cannot safely delete that array.请注意,允许任何人设置Number的数字数组的公共 function setArr从根本上是错误的,因为这意味着您无法知道特定数字的数组来自何处,因此您无法安全地删除该数组。 Same goes for the constructor that takes a digit array as a parameter.将数字数组作为参数的构造函数也是如此。

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

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