Typecasting malloc C++ [duplicate] - c++

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.

Related

C++, modify value on the heap VS delete and new

In a class example in a C++ book, there is an overloading of the assignment operator with the following lines:
delete m_pName;
m_pName = new string(*(c.m_pName));
What is wrong with, instead, simply change the value in the already allocated space?
*m_pName = *(c.m_pName);
Thank you.
There is nothing wrong with your approach. In fact I would use it.
I would even question why there is a std::string*, why isn't it a std::string or a std::optional<std::string>?
The only difference that I see is that the original code makes sure that the memory is freed and freshly allocated. Your approach might reuse alloacted memory and not free up extra space that was allocated and that is now not needed anymore (because the new string is shorter).
Side note: having raw owning pointers is not modern C++. Better use smart pointers like std::unique_ptr.
What is wrong with, instead, simply change the value in the already allocated space?
It does a (slightly) different thing. If that different thing isn't what the function is supposed to do, then it's the wrong thing to do.
So, it boils down to what you're trying/supposed to do. That determines whether what you're doing is wrong or correct. Given that you haven't described what you're trying to do, it is unclear why you think the suggested function would be wrong.
P.S. Avoid bare owning pointers. Prefer RAII classes such as smart pointers or containers instead.
P.P.S. Avoid unnecessary dynamic allocation. There's hardly ever a need to dynamically allocate a std::string.
So in conclusion, perhaps what you should actually be using is something like the following:
struct example {
std::string name;
};
Note that the assignment operator is generated implicitly.

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).

Precautions while using pointers? [duplicate]

This question already has answers here:
What are the barriers to understanding pointers and what can be done to overcome them? [closed]
(28 answers)
Closed 9 years ago.
Pointers are the core to programming languages like C and C++. This at the same time leads to many errors and memory leaks.
What are some precautions that must be taken while using pointers in C and C++?
Always initialize them
Check the bounds (size of pointer offset / index)
free the memory when done
Set to NULL after freeing
Check they are not NULL before accessing
When you malloc, use thing = malloc(N * sizeof *thing)
Don't overwrite a pointer that was malloced before you free it.
...
Some good advice there in the comments and Floris' answer, but IMO "Don't use pointers" isn't one of them
shared_ptrs are great to protect against leaks but you can't always use them. For example you are not supposed to use them with boost::intrusive containers.
additionally shared_ptrs wont help you if you have a container of said shared_ptrs and you just add but never remove from the container. You still "leak" the resources, though you haven't lost the ability to remove it.
other misc hints:
As with all resources I find it best to minimize the code-paths by which one type can be allocated & freed, so that I can match them up in review and/or instrumentation.
when allocating c-strings don't forget to reserve room for your terminator
Pointers are the core to programming languages like C and C++.
Not 'pointers' necessarily, let's talk about references ...
Note(!) that the role of 'pointers' has changed radically, when it comes to paradigms used in c vs. c++ (especially for c++11 language standards). So it would be difficult to handle them equally,
As for c++:
The usage of 'raw' c pointers is strongly discouraged with programming in c++, at least when these are to be allocated dynamically with new() or new[]() (which are the main point of being prone causing memory leaks, within your applications).
In c++ the use of reference (see & and && operators), which aren't available for c, is preferred whenever possible (since they can't lead to such thing as a 'dangling reference' vs. a 'dangling pointer').
The principle introduced in c++ is named RAII, and manages lifetime of any class instances mainly from the call stack scopes of any functions and execution paths present (no matter, if these are called within the same thread or not). I'm not saying that can't be implemented using just plain c, but it's more difficult and error prone.
In a c++ application, the proper memory management for heap allocated class instances should be done using the smart pointer facilitiess of c++11, or at least the use of the good old (meanwhile deprecated) std::auto_ptr class, for pre c++11 standards.
What are some precautions that must be taken while using pointers in C and C++?
There are some use cases for the usage of raw pointers in c++ of course (especially when interfacing between c and c++ APIs), but you should always test for their validity and know pretty good what you're actually doing! All the other cases are nicely covered by c++ standards, and you'll just need to use the right standard smart pointer class to get off from your problems.

Is it secure to use malloc?

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.

When to use Malloc instead of New [duplicate]

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).