VirtualBench C Reference Help

Memory Management

  • Updated2023-09-07
  • 2 minute(s) read

Memory Management

For functions that return data, you must allocate a buffer and specify the size of it. Buffer size is specified as a type of size_t, and is in the units of the data type. For instance, if the function returns data of type uint64_t, the buffer size parameter is the number of uint64_t samples. When returning data, the function returns both the data and the number of samples in the data set. This value can be different than the specified buffer size. If you do not want this value, you can pass NULL for this parameter.

If the buffer size you specify is too small for the amount of data to return, the function fills in the buffer with as much data as it can and returns niVB_Status_Warning_NotEnoughMemory. The parameter for number of samples in the data set indicates the size of the buffer necessary for the data. You can call the function again with this value as the new buffer size to return a buffer with a complete set of data. Consider niVB_MSO_ReadAnalog with this prototype:

 niVB_Status NIVB_DECL niVB_MSO_ReadAnalog(
  niVB_MSO_InstrumentHandle instrumentHandle,
  double* data,
  size_t dataSize,
  size_t* dataSizeOut,
  size_t* dataStride,
  niVB_Timestamp* initialTimestamp,
  niVB_Timestamp* triggerTimestamp,
  niVB_MSO_TriggerReason* triggerReason);

If you want to call this function but do not know how large of a buffer you need, you can call the function specifying NULL for the data and 0 for the buffer size. The function returns the buffer size needed in the parameter for number of samples in the data set. You can then use this value to appropriately size the buffer, then call the function again specifying this buffer and the returned size. The following code example illustrates how you can do this:

 double* data;
 size_t dataSizeOut;

 niVB_MSO_ReadAnalog(instrumentHandle, NULL, 0, &dataSizeOut, &dataStride, &initialTimestamp, &triggerTimestamp, &triggerReason);
 data = (double*)malloc(dataSizeOut*sizeof(double));
 niVB_MSO_ReadAnalog(instrumentHandle, data, dataSizeOut, NULL, &dataStride, &initialTimestamp, &triggerTimestamp, &triggerReason);

You can also preallocate a buffer. Consider a scenario where the acquisition has 200 samples available and the following code is executed.

 double data[100];
 size_t dataSizeOut;

 niVB_MSO_ReadAnalog(instrumentHandle, data, sizeof(data)/sizeof(data[0]), &dataSizeOut, &dataStride, &initialTimestamp, &triggerTimestamp, &triggerReason);

In this case the value of dataSizeOut is set to 200 and the function returns niVB_Status_Warning_NotEnoughMemory. You can now allocate a new buffer of the correct size and call the function again.