Use of free() in PIC Microcontroller Programming

cmicrocontrollermplab

In my Microcontroller PIC18f4550 code, I am using a function which returns an array, I know, C doesn't allow to return an array so I am just returning the address using pointers. Now after the address is returned and performing some action on them, I am freeing the address value I stored in the pointer variable so that the function can be called again and new array address can be passed.

My code(Just to explain):-

int *a,ans[5];

while(1)
{
a=returnarray();
for(j=1;j<5;j++)
       {
          ans[j]=*(a+j);
       }
free(a);
}

My problem:-

I am using MPLABX with XC8 compiler and I am getting error shown on the free() statement, so is there a substitute for this function that I can use here or is there any other way I can perform this task.

Thank you.

Best Answer

free() is always used in combination with malloc(). They both concern dynamic memory on the heap. If you look at section 5.5.7 of the XC8 C Compiler User's Guide:

Dynamic memory allocation, (heap-based allocation using malloc, etc.) is not supported on any 8-bit device. This is due to the limited amount of data memory, and that this memory is banked. The wasteful nature of dynamic memory allocation does not suit itself to the 8-bit PIC device architectures.

If you set the right, high, level of optimization (presuming you have the standard / pro version of the compiler), the compiler might see when the memory isn't needed anymore and rewrite it if necessary. This is only possible if your code is not too complicated.

With a low level of optimization, the compiler won't recognise this and the variable will behave as normally, its memory will be freed when the function in which it's a local variable returns (as with all variables on the stack). If this is in the main() function or we're talking about a global variable, that means never.