… Therefore, when returning a DLL-created string or floating-point
array, you have the following choices:
- Set a persistent pointer to a dynamically allocated buffer, return the pointer. On the next call to the function (1) check that the
pointer is not null, (2) free the resources allocated on the previous
call and reset the pointer to null, (3) reuse the pointer for a newly
allocated block of memory. …
I get the following error dialog when I call free:
MSVC++ Debug Library HEAP CORRUPTION DETECTED: after Normal
block(#135) at 0x……. CRT detected that the application wrote to
memory after end of healp buffer.
Here’s my code:
FP * g_FP;
extern "C" FP * __stdcall xllFill(long rows, long cols) {
if (g_FP != NULL) {
free(g_FP);
g_FP = NULL;
}
g_FP = (FP *)malloc(rows * cols * sizeof(double) + 2 * sizeof(unsigned short int));
for (int i = 0; i < rows * cols; i++) {
(*g_FP).data[i] = (double)i;
}
(*g_FP).rows = (unsigned short int)rows;
(*g_FP).cols = (unsigned short int)cols;
return g_FP;
}
I’m a bit rusty on C++ but I can’t figure for the life of me why this isn’t working.
FPis declared like this:You are assuming that
FPis packed and contains no padding. I don’t know how XLLs are meant to be compiled but I think it is very likely that there is padding betweencolumnsandarrayto arrange thatarrayis 8 byte aligned. With default settings, MSVC returns 16 forsizeof(FP)which supports my hypothesis.Change your allocation to this:
Even if this isn’t the cause of your problem, the allocation above is the logically correct form.
Otherwise I cannot see anything wrong with your code. I think you could be more explicit in initialising
g_FPtoNULLbut that’s a minor point.