Passing memory from C++ to C

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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
 
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
 
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 said:
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
 
Back
Top