Fix potential infinite loop bug

use our own 'realloc' wrapper
Fix and rearrenge include headers and fix some others warnings