Can anyone give me a sample code for allocating memory using malloc? IDE: mplab x ide Compiler: XC16 compiler MCU: PIC24F
Thanks in advance.
Using malloc etc. is the same as in any C implementation. By default, however, the linker in XC16 will not allocate a heap (from which memory for malloc is taken). You will need to tell the linker to allocate a heap in Project Properties|xc16-lc|General|Heap size. The size of the heap must be larger than the largest memory allocations you are making, plus some overhead (see XC16 documentation for details).
Keep in mind that a lot of malloc/ralloc activity may fragment the heap, and your heap is not large. So, be mindful of this. A good strategy is to use the heap like a LIFO buffer (i.e. always free memory in the reverse order that it was allocated).
Can anyone give me a sample code for allocating memory using malloc?
/*
* XC16 v1.31
* PIC24FJ128GB606
* MPLAB X IDE v3.65
* Simulator Debugger
*/
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
volatile int i=0;
int main ()
{
volatile int *ptr= malloc(100*sizeof(int));
if (ptr == NULL)
printf ("Cannot allocate memory\n");
else
{
printf ("Memory Allocated successfully \n");
for (i=0; i<(100*sizeof(int)); i++)
{
*ptr=i;
printf ("Pointer value=%d \t i=%d\n",*ptr++,i);
}
}
free ((void *)ptr);
return 0;
}
Also refer section "Standard C Libraries" under XC16 compiler directory, docs, "16-Bit_Language_Tools_Libraries_Manual.pdf".
malloc()is identical across any platform that supports it. Section 10.3 of the XC16 user manual states with respect to malloc, calloc and ralloc: "If you do not use any of these functions, then you do not need to allocate a heap. By default, a heap is not created.". So if you are having a problem that is probably it, and that is what you should have asked.