I created a MySQL aggregate UDF in C++.
I am returning char*
from the final function of MySQL aggregate UDF.
In the void xxx_deinit(UDF_INIT initid)
I am releasing any memory used by my function.
I am releasing the memory by deleting the init->ptr
.
My deinit function:
extern "C" void xxx_deinit(UDF_INIT * initid)
{
delete initid->ptr;
}
In the init function I am initialing the ptr
like this:
extern "C" bool xxx_init(UDF_INIT * initid, UDF_ARGS * args, char* message)
{
const char* demo = "demo";
initid->ptr = (char*) demo;
return 0;
}
I am able to create the UDF and install it in the MySQL server. After installing when I try to call the function, an error message pops up like this:
Error Code: 2013. Lost connection to MySQL server during query
But when I delete the line: delete initid->ptr;
from the xxx_deinit(UDF_INIT * initid)
function, I get the desired output.
But I am guessing this is the wrong approach because it will lead to a memory leak.
Also, the same statement: delete initid->ptr;
doesn't generate error in case of simple UDF of return type char*
.
Can anyone tell me what am I doing wrong here?
Any kind of help or suggestions will be of great help.
thanks in advance.
Can anyone help me solving this issue.
There is no memory leak, as "demo"
is a pointer to static memory.
You are trying to delete
a pointer to memory that was not allocated with new
. Your runtime has every right to blow up.
The simplest solution is to simply remove the delete
in your deinit function. If you will always put a static string there, that is sufficient.
Alternatively, you can switch to dynamic allocation for the memory of the ptr
member. In the init function:
initid->ptr = strdup("demo");
In the deinit function:
free(initid->ptr);
Note that we use free
instead of delete
, as strdup
allocates memory using malloc
. Never cross new/delete
and malloc/free
!