Computing > Programming

How to change a buffer from main RAM (DATA or BSS) to the heap?

(1/5) > >>

I have this
   static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];

and need to move it to the heap memory. It would be something like

   static uint8_t ucHeap[configTOTAL_HEAP_SIZE] = malloc(configTOTAL_HEAP_SIZE);

but obviously that doesn't compile :)

A stupid Q but no straight answers in many google hits. This is a common example but doesn't compile

   uint8_t* ucHeap = (uint8_t*) malloc(configTOTAL_HEAP_SIZE);

with a "error: initializer element is not constant"

I know for a fact that this works, in the same target, and from stepping through I know that dummy acquires the correct address on the heap

   void *dummy = malloc(configTOTAL_HEAP_SIZE);

You need to do the call of malloc() inside a function.  Global values can only be initialized with constants (or you can use constructors, if you're doing C++)

Edit: change to pointer!
int8_t ucHeap*;

int main() {
   // initialize heap for uccos right away!
   ucHeap = malloc(configTOTAL_HEAP_SIZE);

Surely, the line

int8_t ucHeap[configTOTAL_HEAP_SIZE];

will allocate that in DATA, not on the heap?

Also it doesn't compile, with

warning: type defaults to 'int' in declaration of 'ucHeap' [-Wimplicit-int]
error: conflicting types for 'ucHeap'
warning: initialization of 'int' from 'void *' makes integer from pointer without a cast [-Wint-conversion]
error: initializer element is not constant

You want

--- Code: ---static uint8_t* ucHeap;
int main() { ucHeap = (uint8_t*) malloc(configTOTAL_HEAP_SIZE);

--- End code ---

Wouch. Looks like you need to brush up on your C.

uint8_t* ucHeap = (uint8_t*) malloc(configTOTAL_HEAP_SIZE);

is correct here. (Note that you don't need the (uint8_t*) cast before malloc() in C, malloc() returns a void * which is compatible with any pointer type. In C++, you do need the cast, but then again, using malloc() in C++ is probably just dumb, so trying to make C code using malloc() compilable as C++ doesn't make any sense IMHO.)

But, it is correct in the right context. If you thought of writing the above as a variable declaration at the global level, then it's not correct C. You can't call functions in this context, because global initializers are evaluated at compile time, so you can't use anything that can only be evaluated at run time.

So, if that's what you want to do, you need to declare the pointer at the global level, and then initialize it (with malloc) inside a function, typically one that initializes stuff.

So for instance:

--- Code: ---uint8_t * ucHeap;

void MyInit(void)
    ucHeap = malloc(configTOTAL_HEAP_SIZE);

--- End code ---


[0] Message Index

[#] Next page

There was an error while thanking
Go to full version