Home > OS >  Allocate memory to buffer through function call
Allocate memory to buffer through function call

Time:03-09

I have a function f(q15_t *x, inst *z) it have an input x and an instance z:

typedef struct {
q15_t * pbuff;
}inst;

inst z;

I want an initializer function able to allocate memory space and place it's address to z.pbuff, like (my effort):

instance_initiator(inst *instance,uint16_t buffSize)
{
q15_t a[buffSize];
instance->pbuff=a;
}

I'm searching for correct way to do this, since I think after initiator function finished the buffer allocated spaces will vanishes and it seems we need global variable and this can't happen may be by making a static? I hope to being able to do this.

Note the initialization will run once and the function will be called many times.

As Vlad from Moscow told malloc is good but I feel fear if that is slowing algorithm? Maybe one way is to set the size of static array a by macro.

CodePudding user response:

Allocate using malloc(). Test for success.

// Return error flag
bool instance_initiator(inst *instance, uint16_t buffSize) {
  if (instance == NULL) {
    return true;
  }
  instance->pbuff = malloc(sizeof instance->pbuff[0] * buffSize);
  return instance->pbuff == NULL && buffSize == 0;
}

malloc is good but I feel fear if that is slowing algorithm?

Have no fear. Review Is premature optimization really the root of all evil?.

If you still feel malloc() is slow, post code that demonstrates that.

CodePudding user response:

I've found a solution but I don't know if ever anyone named this solution or not:

#define SIZEOFBUF 500

typedef struct {
q15_t * pbuff;
}inst;

typedef struct {
q15_t buff[SIZEOFBUF];
}instScratch;

inst_initiator(instScratch* scr,inst* z)
{
    inst->pbuff =instScratch->buff
}

void main(void)
{
    static instScratch scr;
    inst z;
    inst_initiator(&inst,&scr);

loop
{
f(x, &z);
}
}

This solution has been possible since static variable's size assumed to be known in compile time, if that wasn't, and the size of buffer determines only in the run time, EZ solution is to use malloc but (as Lundin told) dynamic allocation is forbidden for embedded and you could use Lundin's static memory pool's solution.

  • Related