[HH] c++ strings?

Jerry Feldman gaf at blu.org
Tue Nov 20 12:35:32 EST 2012


On 11/20/2012 10:34 AM, Mark Woodward wrote:
>> Likewise with malloc vs. new: they are NOT freely interchangeable.
>> Managing a C++ class with 'new/delete' will ensure that
>> constructors/destructors get called.  Managing that same object with
>> malloc/free does not invoke constructor/destructor pairs, it merely
>> allocates memory.  Furthermore, there is no guarantee that the way
>> 'new' and 'malloc' manage memory is compatible; e.g. you could have
>> issues if you 'new' and object and then 'free' it, or 'malloc' and
>> object then 'delete' it.
>
> New/delete are interesting. Typically, a pointer returned by "new" can
> be freed by "free," however, new and delete involve the constructors
> and destructors.
>
>
That is very very dangerous. Most C++ implementations I know of layer
new on top of malloc, but the C++ standard leaves that implementation
defined. Using the free(3) library function to free memory allocated by
the C++ new operator can cause the application a lot of problems. The
C++ new operator is not malloc, and while it may use malloc under the
covers, it does other things as does the delete operator. Note that new
and delete are C++ operators, not library functions. Also there are some
cases where C++ may call a default destructor.  So, just because a
pointer returned by the new operator can be freed, it could possibly
lead to a segfault or other issues.

As I mentioned before, every C++ reference states very explicitly that
you should not mix malloc and new. And while virtually every C++
compiler will allow you to do it, it is very poor technique to use
malloc in C++ programs. Mixing stdio and iostream when using stdout and
stderr are not all that dangerous, but when doing file IO, you can get
mixups in file descriptors or even some garbage in a file.

-- 
Jerry Feldman <gaf at blu.org>
Boston Linux and Unix
PGP key id:3BC1EB90 
PGP Key fingerprint: 49E2 C52A FC5A A31F 8D66  C0AF 7CEA 30FC 3BC1 EB90


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 543 bytes
Desc: OpenPGP digital signature
URL: <http://lists.blu.org/pipermail/hardwarehacking/attachments/20121120/55c79539/attachment.sig>


More information about the Hardwarehacking mailing list