Change the memory duration
- Use mi_dalloc() instead of mi_alloc() to
allocate memory.
The mi_dalloc() function works in the same way as mi_alloc() but provides the option of specifying the memory duration of the memory to allocate. This function does not switch the current memory duration.
- Call mi_switch_mem_duration() before you call mi_alloc().
The mi_switch_mem_duration() function switches the current memory duration. All user-memory allocations by subsequent calls to mi_alloc() or mi_zalloc() have the new current memory duration.
Changing the current memory duration with mi_switch_mem_duration() has an effect on the memory durations of all DataBlade® API data type structures that DataBlade API data type structures with the current memory duration lists. It does not have an effect on the memory duration of DataBlade API data type structures allocated at the PER_COMMAND (DataBlade API data type structures with a PER_COMMAND memory duration) and PER_STMT_EXEC (DataBlade API data type structures with a PER_STMT_EXEC memory duration) durations or at the advanced memory durations (DataBlade API data type structures with a PER_SESSION memory duration).
/* Switch current memory duration to PER_COMMAND and save
* old current memory duration in 'old_mem_dur'
*/
old_mem_dur = mi_switch_mem_duration(PER_COMMAND);
/* Perform allocations for a new current memory duration */
buffer = (char *)mi_alloc(BUFF_SIZE);
new_lvarch = mi_new_var(BUFF_SIZE-1);
save_set = mi_save_set_create(conn);
/* Restore old current memory duration */
(void)mi_switch_mem_duration(old_mem_dur);
In the preceding code fragment, the PER_COMMAND memory duration is in effect for the allocation of user memory that the call to mi_alloc() makes. Because the mi_new_var() function allocates a new varying-length structure in the current memory duration, this call to mi_new_var() allocates the varying-length structure with a PER_COMMAND duration. However, the mi_save_set_create() function does not allocate its save-set structure at the current memory duration. Therefore, the call to mi_save_set_create() still allocates its save-set structure with the PER_STMT_EXEC duration. The second call to mi_switch_mem_duration() restores the current memory duration to PER_ROUTINE.