'Allocate memory to buffer through function call
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
