We have a code where over FTP where we create and copy a file. Since we do not know the original size of file - hence as and when data arrives over FTP data socket we first malloc buffer of bigger size - copy old buffered data into new malloced buffer and free the older one.
We observed that while doing this for a file around 4 MB malloc buffer for newly arrived data is success but freeing the old one makes the system to crash.
My assumption is that it could be that stack and dynamically allocated buffer overalps though I am not sure but must be something of same type occuring but how I am not sure. My question is that can stack and dynamically allocated buffer can overalp anytime - if yes how we can know or prevent the same? Also how then malloc is successful?
If the task stack is allocated dynamically it’s also allocated from heap. Heap corruption can be caused if the heap is not threadsafe (that’s not the case when using one of the FreeRTOS provides heap managers - which one do you use ?) or by a programming bug or by a stack overflow.
So you should 1st check if your stack sizes are sufficient (e.g. by enabling FreeRTOS stack checking) and try to track the underlying cause of the crash e.g. by checking the callstack if you’re able to set a breakpoint appropriately.
BTW sometimes it might be better to use preallocated / reserved buffers for such a dedicated purpose like yours to avoid bad side effects like heap fragmentation (if possible resp. dependending on the heap implementation).