I am allocating memory in c++ using new which I am accessing in my go code. Is there any way to delete this memory in go code.
This is the flow of my code :
func f_Go(){
f_C(&buf);//c function
buff := C.GoBytes(unsafe.Pointer(buf), size) //after accessing buf we have to delete buf for avoiding memory leak
}
void f_C(char *buf){
f_C++(&buf);//c++ function
}
void f_C++(char **buf){ //here using new I am allocating memory
*buf = new[20];
memcpy(*buf, "hhhhhhjdfkwejfkjkdj", 20);//cpy content into *buf
}
using like this way I am able to access buf there in go but later we have to delete this memory. So my question is what is the way to delete this memory.
You can export a second function that performs the deallocation. Something like this should do in your C++ file:
extern "C" {
void create_buf(char **buf) {
*buf = new char[20];
...
}
void free_buf(char **buf) {
delete[] *buf;
*buf = nullptr;
}
}
Now you have another function you can call using CGo to perform the clean up.