469,898 Members | 1,448 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,898 developers. It's quick & easy.

Passing memory from C++ to C

I have a C and a CPP program. The C program calls the CPP program. The CPP program needs to pass a new block of memory back to the C program. If I use "new" in the CPP program what do I use in the C program to free the memory? Should I just use malloc in the CPP program? Thanks, Jim
Nov 17 '05 #1
2 1209
>I have a C and a CPP program. The C program calls the CPP program. The CPP program needs to pass a new block of memory back to the C program. If I use "new" in the CPP program what do I use in the C program to free the memory? Should I just use malloc in the CPP program?

Jim,

Do you have 2 programs, or 2 different source modules?

I assume you've got the latter, in which case, you should be fine
using malloc and free since both modules should link to the same
run-time library.

If you've got a situation where you have an application written in 'C'
and a DLL in C++ (or vice-versa), the situation is essentially the
same, but a little more involved as both the EXE & DLL need to be
built with the DLL version of the run-time - so that they use a common
heap.

Dave
--
MVP VC++ FAQ: http://www.mvps.org/vcfaq
Nov 17 '05 #2
As I understand it, memory allocated with malloc() MUST be released with
free(), and memory allocated with new() (which can do MUCH more than
allocate memory, in fact, can do ANYTHING), MUST be released with delete
(exception: managed (__gc garbage collected) classes don't require delete).

So, you CAN'T release memory allocated using new() in a C++ application in
a vanilla C application the 'pointer' returned is passed to. Worse, the
pointer returned from a new() is to the object, while malloc() returns a
pointer to the memory allocated. I'm not sure, but I believe these are not
the same thing.

You must release memory at the same 'level' it was created in.....(sorry,
but that's the way it is)

"Jim Cutler" <an*******@discussions.microsoft.com> wrote in message
news:06**********************************@microsof t.com...
I have a C and a CPP program. The C program calls the CPP program. The

CPP program needs to pass a new block of memory back to the C program. If I
use "new" in the CPP program what do I use in the C program to free the
memory? Should I just use malloc in the CPP program? Thanks, Jim
Nov 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

12 posts views Thread by harry | last post: by
2 posts views Thread by Morgan | last post: by
11 posts views Thread by John Pass | last post: by
12 posts views Thread by Andrew Bullock | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.