Re: Can C pointers take C++ addresses?
Concerning your subject, the answer is a definite 'yes'.
vsykora wrote:
I'm calling C++ functions from C, and been having memory problems.
Specifically, I'm calling a C++ function from C that returns a char*.
I'm allocating memory for the returned pointer in the C++ function,
and trying to free its memory in the C code.
Something as:
// ---------C++ code ------------
extern "C" char* convert() {
char* rvo;
rvo = (char*) malloc(10);
...
return rvo;
}
Please don't use C-style casts in C++, use static_cast here. Also, you
should use initialisation instead of leaving 'rvo' uninitialised and then
assigning to it.
// ---------- C code --------
int main() {
char* s = convert();
free(s);
s = convert();
free(s); // here is the problem!
}
Where is the declaration of convert()? In case you have a
char* convert();
somewhere, you have to make this
char* convert(void);
instead, an empty parameterlist has different meanings in C and C++.
Both functions are compiled independently, and then linked together to
form an executable. I'm getting a "Bus error" when trying to deallocate
the second time, and not sure why.
The problem is not in the code you are showing. It could depend on the code
you don't show (likely) or maybe be caused by you using a C compiler to
link the whole executable. In order to link anything with C++ code, you
should use the C++ compiler. However, this is still dependant on the system
in case, not a requirement of C++ itself.
Is there any problem with this procedure? Is it safe to allocate
memory in C++ code, assign it to C pointers, and then deallocate them
in C?
Yes, this is safe, just be sure to always match malloc() with free() and not
mix with new/delete or new[]/delete[].
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]