Search code examples
cmemory-managementpool

selecting dynamically created memory pools in c


I made a function by which I can create memory pools but how can I select them after creating them?

boolean create_memory_pool(char *name, int size)
{
  boolean result;
  result = false;
  name = malloc(size));
  if( name != NULL)
    result = true;

  return result;
}

In main function if I created more than one 1 memory pools for example

int main()
{
  boolean x;
  x = create_memory_pool( "pool1", 1024);

  x = create_memory_pool( "pool2", 2048);
  x = create_memory_pool( "pool3", 2048);

  // now how to select pool1 or pool2 or pool3
}

what I am trying to do is create a function called select by which I can pass the name of pool and it returns some reference to the pool called.

boolean select( char *name)
{
  //return true if pool of name "name" is selected. 
}

I think I need to declare a global variable X which acts as a reference to currently selected pool which is NULL in the beginning. And on creating each memory pool I can pass the function "select(name)" in the end of "create memory pool" function so on creation of new memory pool it will be automatically selected to the global X. or I can pass the name of any pool which I want to select. but I am stuck in thinking about its implementation.


Solution

  • I have no idea what you're after. I first thought you just wanted strdup(), but I guess not.

    If you want to access the allocated memory by name, then you need to store both the name and the allocated pointer.

    Perhaps something like:

    typedef struct {
      const char *name;
      void *base;
      size_t size;
    } memory_pool;
    

    Then you can implement:

    memory_pool * memory_pool_new(const char *name, size_t size)
    {
      memory_pool *p = malloc(sizeof *p + size);
      if(p != NULL)
      {
        p->name = name; /* Assumes name is string literal. */
        p->base = p + 1;
        p->size = size;
      }
      return p;
    }
    

    Then you can have an array of pools in your main program:

    memory_pool *pools[3];
    pools[0] = memory_pool_new("foo", 17);
    pools[1] = memory_pool_new("bar", 42);
    pools[2] = memory_pool_new("baz", 4711);
    

    Now it's natural to write a function that can find a memory pool by name, in an arary:

    memory_pool memory_pool_array_find(memory_pool **pools, size_t num,
                                       const char *name)
    {
      for(size_t i = 0; i < num; ++i)
      {
        if(strmcp(pools[i]->name, name) == 0)
          return pools[i];
      }
      return NULL;
    }
    

    You can then use the above to find one of the pools you created:

    memory_pool *foo = memory_pool_array_find(pools, 3, "foo");
    if(foo != NULL)
      printf("found the memory pool %s, size %zu\n", foo->name, foo->size);