Best way do delete memory leaks [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In Win32 Console Application (Visual C++) I have a array of objects and each object contains some other objects and variables, ex. (Owner and Equipment are structs, TimeInfo is class):
class Order
{
public:
Order();
~Order();
Owner owner;
Equipment equipment;
char *problem;
TimeInfo timeinfo;
void write();
int order_number;
};
Next I have class OrderManager, that contains the array of this object:
items = (Order*)(malloc(100 * sizeof(Order)));
In program, I add and remove items, but what is the best way to free memory at the end of program? I have free(manager.items);, but this doesn't work.

As people have already pointed out, you should avoid using malloc in this situation. If you want to allocate 100 instances of Order, you could try something like this:
Order* items = new Order[100];
In this case the default constructor of Order is called for every instance.
When you want to free up the memory, you do:
delete[] items; // note the "[]"
Presumably, you want to handle the Orders within an OrderManager, so a typical place for the new/delete would be in the construtor/destructor of the OrderManager.
When using new and delete, the con- and destructors will be called.
It is important that the con- and destructors are called, since they are typically used to set up and initialize things on construction and release things on destruction.
With malloc and free, all that happens is the allocation of memory on the heap.
In your question you mentioned that
free(manager.items);
does not work. Shouldn't you be freeing the pointer items in stead of manager.items?

I would use a destructor to manage freeing memory allocated in the OrderManager class.
You should be using C++ new and delete to allocate/deallocate memory and also should be using containers to store collections of an object.
Refer to this link for a list of options on how you can initialize the vector:
https://stackoverflow.com/a/6143009/3817744
class OrderManager {
private:
std::vector<Order> items;
public:
OrderManager() {
// Refer to the link above
}
~OrderManager() {
items.clear();
}
}
Here is a link to an interesting post about C++'s new operator by David Mazières. http://www.scs.stanford.edu/~dm/home/papers/c++-new.html

Related

How to delete function parameter? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
After calling and using the function, I can access the parameters through the pointer. And I think the parameters are kept in memory. I'm trying to delete the parameters after using the code below.
int MyFunction(int p1,int p2)
{
int total = p1 + p2;
delete& p1;
delete& p2;
return total;
}
and using this
int a = MyFunction(15, 30);
(my project name) initiated a breakpoint.I get an error. How do I delete parameters ?
Your function parameters are passed by value, so they are allocated automatically, not dynamically. You cannot delete them. Being automatically allocated, they will also be automatically deallocated when the function returns, so just skip trying to delete them and go straight to returning.
You can only delete objects allocated on heap (via new).
The parameters to the function are allocated on stack before function call and the runtime "removes" them once the function exits.
(The removal just means that the stack pointer is moved to look as if the parameters no longer exist)
How to delete function parameter?
In general, you shouldn't delete arbitrary variables. You should only delete pointers that you explicitly allocated with new somewhere else in your code.

Template class buffer destructor c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a template class Array that has a buffer type vector.
template <typename T>
class Array
{
protected:
std::vector<T> buffer;
......
}
I want to implement the destructor ~Array(); for this buffer. Any ideas on how to do it?
The default destructor is already releasing the memory of vector, you don't need to define one here.
If you want to free memory of the vector explicitly, then try swap technique whenever you want:
std::vector<T>().swap(buffer);
Any ideas on how to do it?
It depends completely on what you've designed the class and its destructor to do.
The best option, when ever it does what is needed, is to not have a user declared destructor at all, but the implicitly generated one instead. In other words, follow the rule of 0 when possible.
I want to delete the allocated memory of the buffer
All member variables are destroyed automatically. The destructor of the vector deallocates its internal buffer. There is no need for a custom destructor here.

Global class variable vs pointer in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Lets assume I have the following class:
class A
{
public:
A() {}
};
I need to declare a global instance of class A (required by spec.), what works better?
A a; // is the constructor even called here?
or
A* pa; // and allocate later a new instance
Thanks in advance
"A a; - is the constructor even called here?" - yes, the constructor is called.
"* pa; - and allocate later a new instance" - if you actually assign something to this pointer variable before using it, then it can work. But do you?
In general I'd say that the need for global variables indicate a flaw in the design. But if you really have to have them, then make sure they are constructed before you use them.
If A a is used, there would not be a need to release memory allocated to a. When the main() function exits, the destructor for A will be automatically called.
If A *pa is used, ideally pa should be explicitly deleted at some point in the code with delete pa and care should be taken to not use pa after it has been deleted.

Is it useful to create pointer(s) on the heap? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is it useful to create a pointer or an array of pointers on the heap ? if so when and why would I need to do so ?
For example:
#include <iostream>
class Box { /* things... */ };
int main(void){
// Single pointer on the heap
Box** pBox = new Box*(nullptr);
*pBox = new Box();
// Array of pointers on the heap
Box** pBoxes = new Box*[3]{};
pBoxes[0] = new Box();
pBoxes[1] = new Box();
pBoxes[2] = new Box();
// Delete pointers...
return 0;
}
EDIT: Just to make my question more clear ... I know dealing with raw pointers is not the best practice ... I just want to fully understand pointers and their uses as they are important part of c++ hence my question is (is it useful...).
The reasoning behind allocating any memory space on the heap or on the stack is not related to the type of variables allocated, it's related to how it's allocated and how it's meant to be used.
In any case, nowadays you should usually avoid new statements and use "managed" pointers, particularly the std::xxx variants.
From what i read, the heap has slower access speed than the stack so, I don't think that it is very useful to do what you are talking about.
Maybe this will help you trought your research: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
As another answer mentioned, usually actual access to the heap is slower than access to the stack, however access speed generally isn't the reason for creating and dealing with pointers.
The typical use case for pointers is to avoid copying data. When you're dealing with large objects and passing them between many functions, it is considered "better" to pass by reference rather than by value.
If you use the object from the stack (unless you pass it as a reference, but there are limitations when doing this) it makes a copy of the whole thing for the called method. When passing a pointer to a method, it is only copying an address.
See if this article helps you understand the differences.
Yes, there can be reasons to have pointers on the heap. A factory function that keeps track of every object it creates might store them in a vector, for example:
vector<unique_ptr<Box>> BoxFactory::allBoxes;
Box* BoxFactory::makeBox()
{
allBoxes.emplace_back(make_unique<Box>());
return allBoxes.back().get();
}
Note: some people have suggested that this is not double-indirection. It is:
// Accesses some_box_member of the first Box.
allBoxes.data()->get()->some_box_member
Just as with the OP's example, you have two pointers in play, not just one. The vector contains pointers which have been allocated on the heap, and those pointers contain another pointer that points to the Box object.

Deleting multiple pointers with single delete operator [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For deleting and an array of element we use delete[].
Is it possible to delete the pointers the way I am doing below?
ClassA* object = new ClassA();
ClassA* pointer1 = object;
ClassA* object2 = new ClassA();
ClassA* pointer2 = object2;
delete pointer1,pointer2;
Why its not possible to use delete this way?
[Edit]
Can I put it like, what are the drawbacks due to which the above delete has not been implemented?
It's not possible, because there is no provision for it in the C++ language definition. I'm not sure there is any "good" answer to why the language doesn't support a list of items for delete, except for the fact that it's simpler to not do that.
You need to write one delete for each variable. Of course, if you have many pointerX, then you probably should be using an array instead, and use a loop to delete the objects.
Edit: Of course, if you are calling delete in many places in your code, you are probably doing something wrong - or at least, you are not following the RAII principles very well. It's of course necessary to learn/understand dynamic allocation to have full understanding of the language, but you should really avoid calling both new and delete in your own code - let someone else sort that out (or write classes that do "the right thing")
It is not working this way. delete is a command for a single pointer. You can put the pointers in a structure (e.g. array) or a container (e.g. using a vector container class) and delete for each one of them by iterating the structure/container.