I am writing a simple task scheduler and using dynamic memory allocation on my cc430F5137. I agree that it is not a good practice but for the time being lets assume it is my application requirement to use dynamic memory allocation.
In my OS.c file
I have two structures,
typedef struct
{
task_t task;
uint8_t next;
uint8_t prev;
uint8_t priority;
} info_t;
typedef struct
{
task_t task;
uint8_t index;
} index_t;
size of info_t
is 8 bytes and size of index_t
is 6 bytes.
Also I do
index_t* m_index;
info_t* m_info;
Then I have initialize function in which I do
m_info = NULL;
m_index = NULL;
Now I have a function registerTask(& task)
which takes address of the function to schedule. In this function I do
m_info = realloc(m_info,(num_registered_tasks + 1) * sizeof(*m_info));
and then set the values of .priority, next,task and prev.
Then I do
m_index = realloc(m_index,(num_registered_tasks + 1) * sizeof(*m_index));
and set the values of task and index.
and do num_registered_tasks++;
My Question is that how is realloc()
behaving in this regard.
Suppose my memory space,
First Task is registered, so It will have first 8 bytes for m_info[0]
and next 6 bytes for m_index[0]
.
Now when my second task calls this function, what will happen? What I am guessing is that for m_info it will first look for 16 bytes of continuous data and will only find it after the first 14 bytes, it will change the address of m_info[0]
and copy the contents and then add m_info[1]
. And when m_index
is called, it will only find 12 bytes after this (14 + 16) bytes and place m_index[0]
and m_index[1]
here.
If this is true then all my previous space is being wasted?
If I am wrong then how will this function work?
How can I utilize the previous space also?
I need index_t
struct for implementing some sort of search algorithm so it is necessary also