maedoc / libtvb

TVB C library
6 stars 8 forks source link

Registered pointers in malloc. #107

Open maedoc opened 8 years ago

maedoc commented 8 years ago

Users can set custom allocators so all allocations by the C library goes through sd_malloc instead of malloc. In bindings to high-level languages, it would be a worthwhile safety feature, to check if a pointer is in fact a valid pointer, i.e. in a region allocated by sd_malloc.

Proposed API to add:

/* initialize & finalize register */
void sd_malloc_reg_init();
void sd_malloc_reg_fin();

/* return SD_OK if valid pointer, SD_ERR if invalid, SD_UNKNOWN if we dont' know
    (because register inactive for example) */
sd_stat sd_malloc_reg_query(void *);

This requires add SD_UNKNOWN to the sd_stat enum as well.

AbheekG commented 8 years ago

@maedoc I have almost implemented this feature using linked-lists. what is the work of sd_malloc_reg_fin(). sd_malloc_reg_init() initializes the linked list? and sd_malloc_reg_query(void *) does the query.

I have only the sd_malloc_reg_query(void *) and one function for pushing and one for freeing. Hopefully I am doing what is intended.

P.S. Relevant if not already implemented by you.

maedoc commented 8 years ago

@abheekg sd_malloc_reg_fin should free the memory using for the linked list, so you've already implemented it I guess.

I remembered a tricky point that I forgot to write earlier: a pointer may not be necessarily at the start of a region allocated by malloc but somewhere inside. This means we need to track the sizes of the allocations, and sd_malloc_reg_query should check that the pointer is inside at least one of our allocated regions.

Feel free to send a PR and we can look at the code together.