How to delete function parameter? [closed] - c++

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.

Related

How to initialize array of pointers to classes? [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 4 years ago.
Improve this question
given class (for example in name of X) , I want to allocate array like that:
X** array=new X*[20];
Let's look about the following function:
void Func(){
X** array=new X*[2];
X[0]=& X(5);
X[1]=& X(3);
}
Is it OK to do it like that or that I must to do it with new?
The thing is, when you do something like this :
X foo(5);
X[0] = &foo;
(wich i suppose is what you want to say)
X[0] will take the adress of foo, wich is a local variable who will only exist in the scope of your function. And if i do not tell bullshit, does not compile. (-fpermissive)
So after the last instruction of your function, the usage of this pointer will be Undefined
You can't be sure after any allocation that the content of your data is equal to nullptr (if not initialise yet). Initialisation syntax have way different behavior depending language, compiler, stars position etc (just kidding for the last one) so make sure to read the documentation about it.
However you can be sure to init something with null Value by using a zero-initialisation. Link here
If you don't want to dynamicly allocate your array of pointer make sure that those pointer still valid during the lifetime of your object
Another solution could be to dynamicly allocate them.
X[0] = new X(5);

Return a raw pointer to a smart pointer [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 4 years ago.
Improve this question
I have a script like this:
void main(){
vector<int*> objectCollection;
objectCollection.push_back(1);
objectCollection.push_back(5);
objectCollection.push_back(-4);
vector<int*> newCollection
for(auto* itr: *objectCollection){
std::unique_ptr<int>* obj(new int);
someoperation(*itr,obj);
newCollection->push_back(itr);
}
void someoperation(*int raw, &int processed){
std::unique_prt<int> k(new int);
k= raw+1;
processed = k.release();
}
From here, some operation gives back a "raw pointer" to obj, but obj is in a smart pointer in the script. Is there anyway to make a raw pointer content back to the smart pointer? and then make a vector for the smart pointers?
Hope rephrase makes it more clear
Cheers
You can use std::unique_ptr::get() which returns a raw pointer for the underlying object, while leaving the ownership to the smart pointer. Keep in mind that since the ownership it's still the same, unique_ptr will still try to delete the object when its scope ends, so don't allow someOperation to delete it!
http://en.cppreference.com/w/cpp/memory/unique_ptr/get

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.

Best way do delete memory leaks [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
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

Is there any way to change a variable's address? [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 8 years ago.
Improve this question
I'm trying to make a linked list with a set of data and I'm wondering if there's a way to make a variable's address change. Something like:
for(int i=array.size()-1;i>=0;i--)
{
Node *previous_ptr;
Node *current_ptr = new Node(array[i], previous_ptr);
previous_ptr=current_ptr;
delete current_ptr;
}
So I want current_ptr's address to change (allocate a different spot of memory) so the linked list gets constructed if that's possible. And I can't use alloc for it only new and delete.
Calls of new produce different addresses every time you call it, unless you call delete, in which case the memory becomes reusable, so operator new can return it again.
Your code creates hanging pointers: when you call delete on line 3
Node *current_ptr = new Node(array[i], previous_ptr);
previous_ptr=current_ptr;
delete current_ptr;
the value of current_ptr and previous_ptr immediately become invalid. At the same time, the pointer returned by new becomes eligible for reuse, so you get the same pointer when you call new again.
You should not call delete on anything that you plan to use again.
In addition, previous_ptr declared inside a for loop is not useful, because its value is thrown away on each iteration. If you would like to keep that pointer between iterations, declare it outside the loop.
As far as I know, you cannot change a variables address and it doesn't make any sense to me, if you think about what is happening in the background.
If you need a different address for your data, allocate new memory, store your data a 2nd time and delete the old data.