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).
Related
This question already has answers here:
Closed 13 years ago.
I think we all understand the necessity of delete when reassigning a dynamically-allocated pointer in order to prevent memory leaks. However, I'm curious, to what extent does the C++ mandate the usage of delete? For example, take the following program
int main()
{
int* arr = new int[5];
return 0;
}
While for all intents and purposes no leak occurs here (since your program is ending and the OS will clean up all memory once it returns), but does the standard still require -- or recommend -- the usage of delete[] in this case? If not, would there be any other reason why you would delete[] here?
There is nothing that requires a delete[] in the standard - However, I would say it is a very good guideline to follow.
However, it is better practice to use a delete or delete[] with every new or new[] operation, even if the memory will be cleaned up by the program termination.
Many custom objects will have a destructor that does other logic than just cleaning up the memory. Using delete guarantees the destruction in these cases.
Also, if you ever move around your routines, you are less likely to cause memory leaks in other places in your code.
Dupe of Is there a reason to call delete in C++ when a program is exiting anyway?
Answer is that because of destructors that need to be run, it is sometimes necessary to delete the object before exiting the program. Also, many memory leak detection tools will complain if you don't do this, so to make it easier to find real memory leaks, you should try and delete all of your objects before exiting.
Please see:
When to use "new" and when not to, in C++?
About constructors/destructors and new/delete operators in C++ for custom objects
delete and delete [] the same in Visual C++?
Why is there a special new and delete for arrays?
How to track memory allocations in C++ (especially new/delete)
Array of structs and new / delete
What is the difference between new/delete and malloc/free?
Here no. But as the program gets larger and more complex I would manage my memory so that I can track down bugs faster. The standard says nothing but getting into good habits in the smaller case leads to better code long term.
You are perfectly free to forget to delete things.
Do you like wasting memory?
I don't know the Standard, but there is a whole programming style around this question: crash-only softxare
Theoretically databases or OS kernels should be developed as such, but often it's not really practical to use them like that because on restart there is some cleanup that can be long. Moreover dependent systems (programs inside an OS or database clients) might not be crash-only.
Difference between start-pointers and interior-pointers and in what situation we should prefer one over other?
As a complete guess, a "start-pointer" is a pointer returned by malloc or new[], whereas an "interior-pointer" is a pointer to the middle of the allocation.
If so, then the important difference is that you need to free the start-pointer, not an interior-pointer.
This isn't terminology from the standard, though. "Interior pointer" usually means a pointer into some larger block of memory and I guess/deduce the rest. So, you probably need to provide the context. What book/course/interview is the question from?
I believe Steve Jessop's answer is a correct answer that a start-pointer is a pointer returned by malloc(), etc. And an interior-pointers are pointers to places within that allocation. I cannot improve on his answer, but I will expand on it:
As an example, you might need up to a few thousand instances of some struct as a linked list. Instead of calling malloc() for the struct (or class) as needed, you call malloc() just once to allocate enough for a few thousdand instances. Then you create a free-list (a linked-list of the free instances). You can use and free by moving the instances (moving by adjusting the pointer-links) between the free-list and use list(s). Then, when the program no longer needs any of the instances of the struct, you call free() just on the start-pointer, the one originally returned by malloc().
I came across another definition of interior-pointer in the context of Windows and C++ programming for .NET Windows here: http://www.codeproject.com/Articles/8901/An-overview-of-interior-pointers-in-C-CLI.
In C++ / .NET, an interior-pointer can also mean a pointer to memory in CLI heap, i.e. .NET's managed memory. However, seems to me that it is fundamentally the same idea. With using C++ and C with .NET's manages memory, I suppose we are not concerned with starter-pointers because we will never call free() to deallocate. .NET does the garbage collection for us.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the difference between new/delete and malloc/free?
Could someone please revise/edit the below - the differences between malloc and new - and see if everything is correct, or am I missing something or got something wrong? Thank you,
Both malloc and new are used for Dynamic Memory Allocation.
malloc is a C function, whereas new is a C++ operator.
malloc requires a special typecasting when it allocates memory dynamically,
whereas new does not require any typecasting.
Whenever we use new for allocating memory, it also invokes any required constructors, whereas malloc doesn't do that.
malloc can fail and returns a NULL pointer if memory is exhausted, whereas new never returns a NULL pointer, but indicates failure by throwing an exception instead.
While using malloc, free is the C function used to free up the allocated memory.
While using new, delete is the C++ operator used to free up the allocated memory AND call any required destructors.
Important things to note and remember:
placement new
delete[]
_set_new_handler() function
I would like to add the following with your differences,
malloc" does is allocate memory and return a pointer to it. For whatever reason, the designers of the C language implemented it as a standard library function.
On the Other hand "new" is to instantiate an object, by allocating memory and calling the appropriate constructors. Seems reasonable to me that this function is far more tied to the language than something that simply allocates storage.
new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new.
It looks ok, but you could stress the fact that you should never mix malloc with delete and new with free.
Don't forget new[] and delete[], for array allocation and deallocation respectively.
This question already has answers here:
Closed 13 years ago.
Duplicate of: In what cases do I use malloc vs new?
Just re-reading this question:
What is the difference between "new" and "malloc" and "calloc" in C++?
I checked the answers but nobody answered the question:
When would I use malloc instead of new?
There are a couple of reasons (I can think of two).
Let the best float to the top.
A couple that spring to mind:
When you need code to be portable between C++ and C.
When you are allocating memory in a library that may be called from C, and the C code has to free the allocation.
From the Stroustrup FAQ on new/malloc I posted on that thread:
Whenever you use malloc() you must consider initialization and convertion of the return pointer to a proper type. You will also have to consider if you got the number of bytes right for your use. There is no performance difference between malloc() and new when you take initialization into account.
This should answer your question.
The best reason I can think of to use malloc in C++ is when interacting with a pure C API. Some C APIs I've worked with take ownership of the memory of certain parameters. As such they are responsible for freeing the memory and hence the memory must be free-able via free. Malloc will work for this puprose but not necessarily new.
In C++, just about never. new is usually a wrapper around malloc that calls constructors (if applicable.)
However, at least with Visual C++ 2005 or better, using malloc can actually result in security vulnerabilities over new.
Consider this code:
MyStruct* p = new MyStruct[count];
MyStruct* p = (MyStruct*)malloc(count* sizeof(MyStruct));
They look equivelent. However, the codegen for the first actually checks for an integer overflow in count * sizeof(MyStruct). If count comes from an unstrusted source, it can cause an integer overflow resulting in a small amount of memory being allocated, but then when you use count you overrun the buffer.
Everybody has mentioned (using slightly different words) when using a C library that is going to use free() and there are a lot of those around.
The other situation I see is:
When witting your own memory management (because for some reason that you have discovered through modeling the default is not good enough). You could allocate memory block with malloc and the initialization the objects within the pools using placement new.
One of the reason is that in C++, you can overload the new operator.
If you wanted to be sure to use the system library memory allocation in your code, you could use malloc.
A C++ programmer should rarely if ever need to call malloc. The only reason to do so that I can think of would be a poorly constructed API which expected you to pass in malloc'd memory because it would be doing the free. In your own code, new should always be the equal of malloc.
If the memory is to be released by free() (in your or someone elses code), it's pretty darn required to use malloc.
Otherwise I'm not sure. One contrived case is when you don't want destructor(s) to be run on exit, but in that case you should probably have objects that have a no-op dtor anyway.
You can use malloc when you don't want to have to worry about catching exceptions (or use a non-throwing version of new).
When, if ever, can delete and free be used interchangeably in C++?
My concern is as follows: Say there is an incorrect mixup in the use of malloc/ free and
new/ delete (not to mention new[]/ delete[]). However delete and free doing the same thing;
Fortuitously so this goes uncaught in testing. Later this may lead to a crash in production.
How can I enforce some kind of check to prevent this? Can I be warned if the two are mixed up?
If not at compile time, perhaps some code instrumentation at run time? How would I approach
this?
The intention of this question is to find ways to avoid inadvertent mix up in the usages.
The easy way to not get them mixed up is never to use malloc(), then you will never be tempted to call free(). The infrastructure to create to avoid this problem is called "code review", though in this case a quick "grep malloc(" or "grep free(" on the codebase will probably suffice.
Never. If it works it's by sheer accident of implementation. Do not rely on this behavior.
To answer the second question, if you control both malloc/free and operator new/delete, you can stash extra information to associate with pointers returned by both that tell you how they were allocated. When a pointer is passed to free or operator delete, check to see that it was allocated by the appropriate function. If not, assert or raise an exception or do whatever it is you do to report the mismatch.
Usually this is done by allocating extra memory, e.g., given malloc(size) or operator new(size), you allocate size + additional space and shove extra information in there.
The only way you can ensure you never get them mixed up is by either:
Never using malloc/free in the first place, or
Rely on RAII for your memory allocations. Protect every memory allocation in a RAII object which ensures the memory get correctly and consistently freed when it goes out of scope, or wrap the allocation in a smart pointer.
Manually calling delete or free is just an invitation for bugs.
You should always use new and delete in C++, as only new and delete will call the object's constructor and destructor.
If you find you must use both (for instance, if you're interfacing with a C library), thorough code reviews should carefully scrutinize any uses of free() to determine whether or not they correspond to a malloc(), and whether or not they are being used in a C context.
If I had to codify it, I'd put in the style guide something like this:
free() may be called only on a private pointer field of an object.
malloc()ed buffers (or buffers returned from a C API which caller must free()) must be assigned to a private pointer field of an object.
private pointer fields which hold free()-able buffers must only be used for that purpose.
if you use hungarian notation, add a letter for it (and if you don't, don't).
generally free() will be called only in a destructor, with exceptions when the free()-able buffer is replaced during the lifetime of the object. In that case you can call free() on a value recently copied out of a private field during replacement, rather than on the field value directly.
In other words, stick a wrapper around anything that uses malloc/free. This wrapper could be a single template everyone uses, or you could allow smart pointers with the deletor function set to free(). Then in code review, if you see a call to malloc/free anywhere else, it's wrong.
Basically the best way to stop this being a problem is to be on top of your resource handling in general. In C, people do not have a major problem with accidentally calling free() on streams instead of fclose().
You should always use delete or delete[] when freeing things allocated with new. The same goes for malloc and free.
If using free for deleting new:ed classes the destructor won't be properly called.
Also new and delete doesn't necessarily use malloc/free for its allocations so you might end up corrupting your heap as well.
always use delete for things allocated with new, delete [] for things allocated with new [] and free() for things allocated using malloc().
new and new[] allocate from different heaps than malloc() and using the wrong free()/delete will attempt to deallocate from the wrong heap.
Never mix new/delete with new[]/delete[] or with malloc()/free(). Atop of this, the use of malloc()/free() in C++ is questionable at least.
The easiest way to make sure you never do this accidentally is to not to manage memory manually. In C++ there strings and other containers as well as smart pointers to take care of memory management. There simply isn't a need to do this manually. (I'm not sure whether the last time I remember me typing delete really was the last time I typed it. But if my memory doesn't fail me, this must have been 2001 or 2002.)
You could write your own version of the functions which allocate some extra memory in new/new[]/malloc to track which one did the allocation. Then check in delete/delete[]/free that the right function was used to re-claim the memory. You can also check for things like mixing new[] and delete (without the []) this way. You might want to only use these versions in the debug build.
You could try running valgrind on your application to see if it catches anything. The manual specifically mentions its ability to catch uses of the wrong deallocation function for a block of memory. I don't think there's a way to do this at compile time, however.
One way to avoid misusage of malloc/free or new/delete is that DO NOT call these function directly, call them by a wrapper layer. In the wrapper layer, you can manage the pointers distributed by your own hands and guarantee that misusage will get an error explicitly.
Why dont you just count the total number of malloc statments and tally that with the total count of free? Do the same for New and delete. The process can be automated with regular expressions.
One thing I've done relating to this is to reimplement malloc and free
in C++, so that it calls new/delete under the hood. It's not
optimal, but it serves well enough on a smaller project.