MATLAB: Do I get the error “Corrupted Memory Block” when using the LIBPOINTER function

assertioncrashillegalMATLABmemoryoverwriteprotectedsegmentationviolation

I have an external library which accepts a pointer to a buffer. Therefore, I pass in a LIBPOINTER. When I run my MATLAB code, I receive the following error:
ERROR: Corrupted Memory Block
MATLAB should be able to allocate a buffer of the right size automatically.
I'm executing the following code:
returnStringBuffer = libpointer('int8Ptr', 0);
calllib('testLibrary', 'GetReturnString', returnStringBuffer)

Best Answer

This type of error or crash is usually caused by an external library writing to a memory block that does not provide enough buffering space for the data that is being written.
To work around this issue, consult the external application's documentation to find out what the buffer length should be. In order to access the actual data in the buffer, this type of external function usually returns the size of the data that has been written. Otherwise, if you expect a string, you can find the end of the string because in C, all strings end with the character represented by ASCII code 0 (zero), that's why they are called null-terminated strings.
The documentation of the LIBPOINTER function states the following:
"MATLAB automatically converts data passed to and from external library functions to the data type expected by the external function. The libpointer function enables you to convert your argument data manually. This is an advanced feature available to experienced C programmers."
The function LIBPOINTER offers a way to have more control over your programming by doing everything manually. That's why MATLAB does not take care of any buffering automatically. Actually it is impossible to allocate the memory automatically, because when you pass a pointer to an external library, you are only passing the address to a certain memory location. The passing application, in this case MATLAB, does not know what the external application will do to this memory chunk, it could read something from it or write something, but MATLAB can never know.
The documentation link to various use cases of libpointer is present here: