I make my own C/C++ libraries with some functions written in C; other in C++. Inside the library I use the new
operator:
mystruct * mystruct_alloc()
{
mystruct * ms = new mystruct;
return ms;
}
Now I use this library in C like this:
mystruct *ms = mystruct_alloc();
// do stuff
free(ms);
When I check this with valgrind; I get warnings like this:
Mismatched free() / delete / delete []
But I have the impression that all memory is freed correctly. I know that there are two ways to circumvent this problem.
I could rewrite my C++ code to use malloc:
mystruct * mystruct_alloc()
{
mystruct * ms = (mystruct *) malloc (sizeof(mystruct));
return ms;
}
I could write a dealloc
function in my library:
void mystruct_dealloc(mystruct *ms)
{
delete ms;
}
and I would have no more problems; but what is the best way? new
is easier to use; but it gives those warnings in valgrind. So here are my questions:
- Is all memory freed correctly if I use
new
andfree
? (so the valgrind warning is not very important) - Is there a preferred way to program this?
You always should return memory in the corresponding way to how you got it:
free
formalloc
delete
for rawnew
operator delete
for a user definedoperator new
In your case, write and call a corresponding function in your C++ library: