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).
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.
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).
This question already has answers here:
Do I cast the result of malloc?
(29 answers)
Closed 9 years ago.
I have some C code with malloc statements in it that I want to merge with some C++ code.
I was wondering when and why is typecasting a call to malloc neccessary in C++?
For example:
char *str = (char*)malloc(strlen(argv[1]) * sizeof(char));
when and why is typecasting a call to malloc neccessary in C++?
Always when not assigning to a void *, since void * doesn't convert implicitly to other pointer types, the way it does in C. But the true answer is you shouldn't ever use malloc in C++ in the first place.
I am not suggesting you should use new instead of malloc. Modern C++ code should use new sparingly, or avoid it altogether if possible. You should hide all use of new or use non-primitive types (like std::vector mentioned by Xeo). I'm not really qualified to give advice in this direction due to my limited experience but this article along with searching for "C++ avoid new" should help. Then you'll want to look into:
std::alocator
Smart pointers
Compile your C library. Compile your C++ library. Make them play nice in whatever "main" program that uses them. Point is if your maintaining a mixed code base, you probably want to isolate the pure C stuff from the C++ stuff. Otherwise your C stuff turns into C++ stuff that only looks like C.
First, in almost all circumstances just don't use malloc in a C++ program, but prefer new instead because it will make sure that constructors are called when needed, etc.
However if for legacy reasons you're trying to avoid as much rewrite as possible - you'll need to cast any malloc call that's not assigned to a void* pointer.
If you can change that code its probably better to use new instead so it would look like this
char* str = new char;
this means you don't need to do any casting like the C way and you don't need to specify how large the memory you need. Also if this was an object like a std::string then you WILL not call the constructor when you use malloc, this merely reserves the memory for use with the pointer str so best always use new with C++ if you can also when you reclaim memory always use the appropriate way, if you new then you delete and if you malloc you free. If you use free on memory that has been new'd then you won't call that objects destructor.
malloc always returns a void* so you need to cast everything (because C++ has stronger type checking than C and don't this automatically)
When I am using C, I also cast everything, for code clarity.
Also, feel free to keep using malloc() in C++, it is there for a good reason.
Converting all the C code to C++ by rewriting every single malloc() to new is very prone to introduce lots of errors in your code, unless you have the time to keep reading the code you are merging to find every single instance of malloc(), free(), calloc(), etc... on it.
Just don't mix malloc() with delete or new with free() or things break.
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.
Somebody told me that allocating with malloc is not secure anymore, I'm not a C/C++ guru but I've made some stuff with malloc and C/C++. Does anyone know about what risks I'm into?
Quoting him:
[..] But indeed the weak point of C/C++ it is the security, and the Achilles' heel is indeed malloc and the abuse of pointers. C/C++ it is a well known insecure language. [..] There would be few apps in what I would not recommend to continue programming with C++."
It's probably true that C++'s new is safer than malloc(), but that doesn't automatically make malloc() more unsafe than it was before. Did your friend say why he considers it insecure?
However, here's a few things you should pay attention to:
1) With C++, you do need to be careful when you use malloc()/free() and new/delete side-by-side in the same program. This is possible and permissible, but everything that was allocated with malloc() must be freed with free(), and not with delete. Similarly, everything that was allocated with new must be freed with delete, and never with free(). (This logic goes even further: If you allocate an array with new[], you must free it with delete[], and not just with delete.) Always use corresponding counterparts for allocation and deallocation, per object.
int* ni = new int;
free(ni); // ERROR: don't do this!
delete ni; // OK
int* mi = (int*)malloc(sizeof(int));
delete mi; // ERROR!
free(mi); // OK
2) malloc() and new (speaking again of C++) don't do exactly the same thing. malloc() just gives you a chunk of memory to use; new will additionally call a contructor (if available). Similarly, delete will call a destructor (if available), while free() won't. This could lead to problems, such as incorrectly initialized objects (because the constructor wasn' called) or un-freed resources (because the destructor wasn't called).
3) C++'s new also takes care of allocating the right amount of memory for the type specified, while you need to calculate this yourself with malloc():
int *ni = new int;
int *mi = (int*)malloc(sizeof(int)); // required amount of memory must be
// explicitly specified!
// (in some situations, you can make this
// a little safer against code changes by
// writing sizeof(*mi) instead.)
Conclusion:
In C++, new/delete should be preferred over malloc()/free() where possible. (In C, new/delete is not available, so the choice would be obvious there.)
[...] C/C++ it is a well known insecure language. [...]
Actually, that's wrong. Actually, "C/C++" doesn't even exist. There's C, and there's C++. They share some (or, if you want, a lot of) syntax, but they are indeed very different languages.
One thing they differ in vastly is their way to manage dynamic memory. The C way is indeed using malloc()/free() and if you need dynamic memory there's very little else you can do but use them (or a few siblings of malloc()).
The C++ way is to not to (manually) deal with dynamic resources (of which memory is but one) at all. Resource management is handed to a few well-implemented and -tested classes, preferably from the standard library, and then done automatically. For example, instead of manually dealing with zero-terminated character buffers, there's std::string, instead of manually dealing with dynamically allocated arrays, there std:vector, instead of manually dealing with open files, there's the std::fstream family of streams etc.
Your friend could be talking about:
The safety of using pointers in general. For example in C++ if you're allocating an array of char with malloc, question why you aren't using a string or vector. Pointers aren't insecure, but code that's buggy due to incorrect use of pointers is.
Something about malloc in particular. Most OSes clear memory before first handing it to a process, for security reasons. Otherwise, sensitive data from one app, could be leaked to another app. On OSes that don't do that, you could argue that there's an insecurity related to malloc. It's really more related to free.
It's also possible your friend doesn't know what he's talking about. When someone says "X is insecure", my response is, "in what way?".
Maybe your friend is older, and isn't familiar with how things work now - I used to think C and C++ were effectively the same until I discovered many new things about the language that have come out in the last 10 years (most of my teachers were old-school Bell Laboratories guys who wrote primarily in C and had only a cursory knowledge of C++ - and Bell Laboratories engineers invented C++!). Don't laugh at him/her - you might be there someday too!
I think your friend is uncomfortable with the idea that you have to do your own memory management - ie, its easy to make mistakes. In that regard, it is insecure and he/she is correct... However, that insecure aspect can be overcome with good programming practices, like RAII and using smart pointers.
For many applications, though, having automated garbage collection is probably fine, and some programmers are confused about how pointers work, so as far as getting new, inexperienced developers to program effectively in C/C++ without some training might be difficult. Which is maybe why your friend thinks C/C++ should be avoided.
It's the only way to allocate and deallocate memory in C natively. If you misuse it, it can be as insecure as anything else. Microsoft provides some "secure" versions of other functions, that take an extra size_t parametre - maybe your friend was referring to something similar? If that's the case, perhaps he simply prefers calloc() over malloc()?
If you are using C, you have to use malloc to allocate memory, unless you have a third-party library that will allocate / manage your memory for you.
Certainly your friend has a point that it is difficult to write secure code in C, especially when you are allocating memory and dealing with buffers. But we all know that, right? :)
What he maybe wanted to warn you is about pointers usage. Yes, that will cause problems if you don't understand how it works. Otherwise, ask what your friend meant, or ask him for a reference that proof his affirmation.
Saying that malloc is not safe is like saying "don't use system X because it's insecure".
Until that, use malloc in C, and new in C++.
If you use malloc in C++, people will look mad at you, but that's fine in very specific occasions.
There is nothing wrong with malloc as such. Your friend apparently means that manual memory management is insecure and easily leads to bugs. Compared to other languages where the memory is managed automatically by a garbage collector (not that it is not possible to have leaks - nowadays nobody cares if the program cleans up when it terminates, what matters is that something is not hogging memory while the program is running).
Of course in C++ you wouldn't really touch malloc at all (because it simply isn't functionally equivalent to new and just doesn't do what you need, assuming most of the time you don't want just to get raw memory). And in addition, it is completely possible to program using techniques which almost entirely eliminate the possibility of memory leaks and corruption (RAII), but that takes expertise.
Technically speaking, malloc was never secure to begin with, but that aside, the only thing I can think of is the infamous "OOM killer" (OOM = out-of-memory) that the Linux kernel uses. You can read up on it if you want. Other than that, I don't see how malloc itself is inherently insecure.
In C++, there is no such problem if you stick to good conventions. In C, well, practice. Malloc itself is not an inherently insecure function at all - people simply can deal with it's results inadequately.
It is not secure to use malloc because it's not possible to write a large scale application and ensure every malloc is freed in an efficient manner. Thus, you will have tons of memory leaks which may or may not be a problem... but, when you double free, or use the wrong delete etc, undefined behaviour can result. Indeed, using the wrong delete in C++ will typically allow arbitrary code execution.
The ONLY way for code written in a language like C or C++ to be secure is to mathematically prove the entire program with its dependencies factored in.
Modern memory-safe languages are safe from these types of bugs as long as the underlying language implementation isn't vulnerable (which is indeed rare because these are all written in C/C++, but as we move towards hardware JVMs, this problem will go away).
Perhaps the person was referring to the possibility of accessing data via malloc()?
Malloc doesn't affect the contents of the region that it provides, so it MAY be possible to collect data from other processes by mallocing a large area and then scanning the contents.
free() doesn't clear memory either so data paced into dynamically allocated buffers is, in principle, accessible.
I know someone who, many years ago admittedly, exploited malloc to create an inter-process communication scheme when he found that mallocs of equal size would return the address of the most recently free'd block.