Deleting variables that are no longer in use, through the function [duplicate] - c++

This question already has answers here:
Calling delete on variable allocated on the stack
(12 answers)
Closed 8 years ago.
I know that C++ holds memory management internally with a lot of given points, and I know of the delete command to remove dynamically allocated data, and this question, could seem pointless within the fact that it may not ever come to be an issue due to the destruction of variables outside of the scope of the function that is using them, but is it possible to use a function such like delete to remove a variable that the user is no longer putting to use.
Like say that you are on a heavily memory depleted piece of hardware, and need to make sure that even something as small as the 4 bytes that an integer normally takes up are given straight back. Is it possible to do this without wrapping the variable inside some function to make the assembler know to remove it immediately?
This is in a sense of a point that I don't believe could ever happen, due to the expansion of memory, and the ways that it could be manipulated these days, but it seems as if it may have been an issue before, if I'm not mistaken.
Summary:
Is there a way to manage non dynamic data directly, allocate it to the stack, and remove it from the stack through a function call, or is this completely run by the programs internal instructions?
Example:
void foo(){
short int operator;
/*Did what needed to be done with the operator variable***********/
//Pseudo-code
delete operator;
/*Even though it was not allocated dynamically,
and with the use of another function call*/
}

As you said, easy way of doing this would just be to put variable in lower scope and allow it to free itself.
If it's any container, you can clear it with appropriate function call.
Basically:
delete what you new, delete[] what you new[].
Also see this:
https://stackoverflow.com/a/441837/2975193

Related

Any possible use of free() with new & delete with malloc()? [duplicate]

This question already has answers here:
new, delete ,malloc & free
(2 answers)
Closed 6 years ago.
In a recent interview, the interviewer asked me if we can use free() to deallocate space which was previously allocated using new. I answered in a yes. :|
I know the pair works like malloc() - free() & new - delete.
But since both utilizes some pointer mechanisms, then what is wrong in intermixing them?
There must be a possibilty to achieve deallocation while intermixing the two pairs. Is it possible? Even in theory? And what could be the possible scenarios to intermix them?
If doing the previously stated point is possible, then why have we introduced delete with new?
Kindly enlighten me on this subject & if there's any source code of new/delete/malloc/free available to you or any thorough guide to grasp this particular topic, please provide the link.
My another curiosity is,  what could be the caveats & problems with delete?
For one thing, they may be using completely different heaps. In more than one application of ours the global new and delete are redefined to perform some additional bookkeeping; if you pass to free a pointer returned by new it won't be recognized as stuff from malloc, because we are keeping extra info at the start of each memory block. The standard library can do the same.
Why should there be? As already said, the memory they return can come from different heaps, so it makes no sense to use one to deallocate stuff from the other. Now, if you are allocating POD types and if the global new operator is just a thin wrapper around malloc, in theory it could accidentally work to use freefor memory allocated with new, but I really don't see the point in doing so besides adding confusion (and potential undefined behavior).
new and delete were introduced as operators to deal with non-POD types. If all you want is "raw" memory malloc (or, in general, a single function) is fine, but if you want to allocate objects stuff gets more complicated; the allocation mechanism must be aware of the type of the allocated data, not just of the required size, because it has to invoke the constructors (the same for delete, which has to invoke destructors, although new could have just saved the function pointer to the destructor).

How does delete[] know how much memory to delete? [duplicate]

This question already has answers here:
How does delete[] "know" the size of the operand array?
(9 answers)
How does delete[] know it's an array?
(16 answers)
Closed 9 years ago.
int* i = new int[4];
delete[] i;
While we call delete[], how does the program know "i" is 4 byte-length. Is 4 be stored in somewhere in memory?
The implementation of delete[] depend on System or Compilers?
Is there some System API to get the length of i?
As HadeS said, which will hold the information how much memory has been allocated? And where?
It must be hold in memory, or maybe nearby the pointer i.
First off, i is not "4-byte length". Rather, i is a pointer to an array of four ints.
Next, delete[] doesn't need to know anything, because int has no destructor. All that has to happen is that the memory needs to be freed, which is done by the system's allocator. This is the same situation as with free(p) -- you don't need to tell free how much memory needs to be freed, since you expect it to figure that out.
The situation is different when destructors need to be called; in that case, the C++ implementation does indeed need to remember the number of C++ objects separately. The method for this is up to the implementation, although many compilers follow the popular Itanium ABI, which allows linking together of object code compiled by those different compilers.
There is no way for you to query this information. You should consider dynamic arrays a misfeature of C++; there is essentially no reason to use them*, and you can always do better with some kind of class that manages memory and object separately and individually: Since you'll have to remember the number of array elements anyway, it's much better to encapsulate the size and the allocation in one coherent class, rather than have vague dynamic arrays that you cannot really use without passing extra information along anyway (unless you had self-terminating semantics, but then you'd just be using the extra space for the terminator).
*) And there are at least two standard defects about dynamic arrays that nobody is too bothered to worry about fixing
When you dynamically allocate a memory; compiler allocates an extra block of memory apart from what you have asked, which will hold the information how much memory has been allocated.
when you try to delete this memory using delete this extra block of memory will be read by the compiler to see how much memory was allocated and free the space accordingly.
I don't think there is any API which will fetch this information.

Allocating a vector vs. a pointer to a vector [duplicate]

This question already has answers here:
Why should C++ programmers minimize use of 'new'?
(19 answers)
Closed 9 years ago.
Say I have two sets of code,
std::vector<float>v1;
and
std::vector<float> *pV2 = new std::vector<float>(10);
What is the difference between the two other than the fact that you will have a larger chunk of memory allocated with the pointer to the vector? Is there an advantage to one vs. the other?
In my mind, it seems like allocating the pointer is just more of a hassle because you have to deal with deallocating it later.
What is the difference between the two other than the fact that you will have a larger chunk of memory allocated with the pointer to the vector?
'will have a larger chunk of memory allocated'
This isn't necessarily true! The std::vector might choose a much larger default initial size for the internally managed data array than 10.
'What is the difference between the two'
The main difference is that the 1st one is allocated on the local scopes stack,
and the 2nd one (usually) goes to the heap. Note: The internally managed data array goes to the heap anyway!!
To ensure proper memory management when you really have to use a std::vector<float>* pointer allocated from the heap, I'd recommend the use of c++ smart pointers, e.g.:
std::unique_ptr<std::vector<float> > pV2(new std::vector<float>(10));
For more details have a look at the documentation of <memory>.
One of the critical differences is scope. In your first example, the vector will probably either be a member of a class, or it will be local to a function. If it's a class member, it will be destroyed when the containing object is destroyed. If it's local to a function, it will be destroyed when the function ends. The object absolutely cannot exist beyond that, so you have to be very careful if you try passing its address to another part of your program.
When you manually allocate something on the heap instead, it will exist for as long as you want. You're in complete control of the deallocation, which means you can create it in one object/function, and use or delete it in another whenever you need to.
It's also quite useful in various situations to be able to delay instantiation of an object until it's actually required. For example, it may need different construction parameters depending on user input, or you may want to take advantage of polymorphism (i.e. decide at runtime which sub-class to instantiate).
Another key difference for some situations is available memory. If you create an object locally to a function, it will reside on the stack. There is a lot less space available on the stack than on the heap, so you can run into difficulties when using particularly large objects (although that won't happen with a vector because it allocates on the heap internally anyway).
It's worth noting that the actual amount of memory used by the object is the same, whether it's on the stack or on the heap. The only difference is that if you manually allocate something on the heap, then you will also have a pointer to it. That's only an extra 4 or 8 bytes though, which is negligible in most cases.

Object Construction Syntax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is difference between instantiating an object using new vs. without
Creating an object: with or without `new`
What is the difference between these two statements
HttpUtil httpUtil;
and
HttpUtil *net = new HttpUtil();
Which one is better to be used?
The first creates an automatic variable. Memory management is automatic, allocation is faster since it's on the stack, there's no chance of a memory leak.
The second version creates a dynamic variable - you're responsible for cleaning up the memory and the allocation is slower on the heap.
Always prefer the first one. If you must use dynamic allocation (for persisting lifetime or polymorphic behavior), use smart pointers instead of raw pointers.
The first statement creates a variable called httpUtil on the 'stack' - this means that, as soon as the function containing that line finishes, the variable goes 'out of scope' and gets released (the memory it uses becomes free to use for other stuff).
The second statement creates a variable on the 'heap' - this means that the variable will remain in memory until you call delete on it. When allocating variables on the heap you need to make sure that you always delete it at some point, otherwise you'll get memory leaks - this is where you can no longer see your *net variable, but the memory is still allocated.
First one is statically created object where you don't need to worry about its destruction.
Later one is dynamically created object where you need to take care of its destruction before application terminates.
First one is preferred where you dont need to worry about memory management.

C++ Pointing to classes

I'm going through a C++ book at the moment and i'm slightly confused about pointing to classes.
Earlier in the book the examples used classes and methods in this way:
Calculator myCalc;
myCalc.launch();
while( myCalc.run() ){
myCalc.readInput();
myCalc.writeOutput();
}
However, now it's changed to doing it this way:
Calculator* myCalc = new Calculator;
myCalc -> launch();
while( myCalc -> run() ){
myCalc -> readInput();
myCalc -> writeOutput();
}
And I can't seem to find an explanation in there as to WHY it is doing it this way.
Why would I want to point to a class in this way, rather than use the standard way of doing it?
What is the difference? And what circumstances would one or the other be preferable?
Thank you.
First, you are not pointing to the class, but to an instance of the class, also called an object. (Pointing to classes is not possible in C++, one of its flaws if you'd ask me).
The difference is the place where the object is allocated. When you're doing:
Calculator myCalc;
The whole object is created on the stack. The stack is the storage for local variables, nested calls and so on, and is often limited to 1 MB or lower. On the other hand, allocations on the stack are faster, as no memory manager call is involved.
When you do:
Calculator *myCalc;
Not much happens, except that a Pointer is allocated on the stack. A pointer is usually 4 or 8 bytes in size (32bit vs. 64bit architectures) and only holds a memory address. You have to allocate an object and make the pointer point to it by doing something like:
myCalc = new Calculator;
which can also be combined into one line like shown in your example. Here, the object is allocated on the heap, which is approximately as large as your phyiscal memory (leaving swap space and architectural limitations unconsidered), so you can store way more data there. But it is slower, as the memory manager needs to kick in and find a spare place on the heap for your object or even needs to get more memory from the operating system. Now the pointer myCalc contains the memory address of the object, so it can be used with the * and the -> operators.
Also you cannot pass pointers or references to objects on the stack outside their scope, as the stack will get cleaned when the scope ends (i.e. at the end of a function for example), thus the object becomes unavailable.
Oh and nearly forgot to mention. Objects on the heap are not automatically destroyed, so you have to delete them manually like this*:
delete myCalc;
So to sum it up: For small, short living objects which are not to leave their scope, you can use stack based allocation, while for larger, long living objects the heap is usually the better place to go.
*: Well, ideally, not like that. Use a smart pointer, like std::unique_ptr.
You use the dot (.) when your variable is an instance or reference of the class while you use -> if your variable is a pointer to an instance of a class.
They are both part of the C++ standard, but there is a core difference. In the first way, your object lives on the stack (which is where functions and local variables are stored, and removed after they are no longer used). When you instead declare your variable type as a pointer, you are only storing a pointer on the stack, and the object itself is going on the heap.
While when you use the stack local variable to allocate the memory, it is automatically taken care of by C++. When it's on the heap, you have to get the memory with new and free it with delete.
While in the stack example your code uses . to call methods, to call methods on a pointer, C++ provides a shortcut: ->, which is equivalent to *obj.method().
Remember, when you use new, always use delete.
Both are standard. One is not preferred over the other.
The first one is typical of local variables that you declare and use in a narrow scope.
The pointer method allows you to dynamically allocate memory and assign it to a pointer type; that's what the "star" notation means. These can be passed out of a method or assigned to a member variable, living on after a method is exited.
But you have to be aware that you are also responsible for cleaning up that memory when you're done with the object the pointer refers to. If you don't, you many eventually exhaust a long-running application with a "memory leak".
Other than the obvious difference in notation/syntax. Pointers are generally useful when passing data into a function.
void myFunc(Calculator *c) {
...
}
is usually preferred over
void myFunc(Calculator c) {
...
}
since the second requires a copy be made of the calculator. A pointer only contains the location to what is being pointed to, so it only refers to another spot in memory instead of containing the data itself. Another good use is for strings, imagine reading a text file and calling functions to process the text, each function would make a copy of the string if it were not a pointer. A pointer is either 4 or 8 bytes depending on the machines architecture so it can save a lot of time and memory when passing it to functions.
In some case though it may be better to work with a copy. Maybe you just want to return an altered version like so
Calculator myFunc(Calculator c) {
...
}
one of the important things about pointers is the "new" keyword. It is not the only way to create a pointer but it is the easiest way that for c++. You should also be able to use a function called malloc() but that is more for structs and c IMO but I have seen both ways.
Speaking of C. Pointers may also be good for arrays. I think you can still only declare the size of an array at compile time in c++ too, but I could be mistaken. You could use the following I believe
Calculator *c;
....
Calculator d = c[index];
So now you have an array which can make it quite ambiguous IMO.
I think that covers just about all I know and in the example provided I do not think there is any difference between the two snippets you provided.
First of all, you are not pointing to a class, you are pointing to an instance (or object) of that class. In some other languages, classes are actually objects too :-)
The example is just that, an example. Most likely you wouldn't use pointers there.
Now, what IS a pointer? A pointer is just a tiny little thing that points to the real thing. Like the nametag on a doorbell -- it shows your name, but it's not actually you. However, because it is not you, you can actually have multiple buttons with your name on it in different locations.
This is one reason for using pointers: if you have one object, but you want to keep pointers to that object in various places. I mean, the real world has tons of "pointers" to you in all sorts of places; it shouldn't be too difficult to imagine that programs might need similar things inside their data.
Pointers are also used to avoid having to copy the object around, which can be an expensive operation. Passing a pointer to functions is much cheaper. Plus, it allows functions to modify the object (note that technically, C++ "references" are pointers as well, it's just a little less obvious and they are more limited).
In addition, objects allocated with "new" will stay around until they are deallocated with "delete". Thus, they don't depend on scoping -- they don't disappear when the function around them finishes, they only disappear when they are told to get lost.
Plus, how would you make a "bag with fruit"? You allocate a "bag" object. Then you allocate a "fruit" object, and you set a pointer inside the bag object to point to the fruit object, indicating that the bag is supposed to contain that fruit. The fruit might also get a pointer to the bag object, just so code working on the fruit can also get to the bag. You can also allocate another "fruit" object, and establish a chain of pointers: each "fruit" could have a single "next" pointer that points to the "next" fruit, so you can put an arbitrary number of fruits into the bag: the bag contains a pointer to the first fruit, and each fruit contains a pointer to another fruit. So you get a whole chain of fruits.
( This is a simple "container"; there are several such classes that "contain" an arbitrary number of objects ).
It's actually not that simple to come up with descriptions of when or why pointers are used; usually there'll just be situations where you'll need them. It's much easier to see their usefulness when you run into such a situation. Like "why is an umbrella useful" -- once you step into the pouring rain outside, the usefulness of an umbrella will become obvious.
One use would be if the variable myCalc has a very long lifetime. You can create it when you need if with new and remove it when done with delete. Then you don't have to worry about carrying it around at times when it's not needed and would only take up space. Or you can reinitialise it at will when needed, etc.
Or when you have a very big class, it's common practice to use new to allocate it on the heap rather than the stack. This is a leftover from the days when stack space was scarce and the heap was larger, so heap space was cheaper.
Or, of course, the most common use, allocating a dynamic array. myCalc = new Calculator[x]; to create x new calculators. You can't do this with static variables if you don't know beforehand how large x is; how many objects you're going to create.