ecmwf-ifs / field_api

Apache License 2.0
3 stars 8 forks source link

0-size allocations for owned fields #25

Closed awnawab closed 8 months ago

awnawab commented 8 months ago

Throughout the IFS, we initialize 0-sized owned fields (a workaround for when a particular field is meant to be disabled). Whilst these 0-sized allocations are safe using the Fortran ALLOCATE statement, they cause errors in C_MALLOC. This PR adds safety checks so that 0-sized allocs can be handled safely using Fortran ALLOCATE/DEALLOCATE.

We need C_MALLOC because there is an upper limit on registering Fortran allocated memory in page-locked memory (which is lower than the OS limit).

pmarguinaud commented 8 months ago

Hello Ahmad,

Why do not you do something like this in c_malloc ?

void c_malloc (size_t siz, void ** ptr)
{
  if (siz == 0)
    siz = 1;
  *ptr = malloc (siz);
}

This would avoid all the logic with SAFE_ALLOC.

awnawab commented 8 months ago

Thanks a lot for the feedback @pmarguinaud! When I tried your suggestion, I was getting "free invalid pointer" errors. These probably arise from when we cast the c pointer as a Fortran pointer. Sadly I think we have to do the allocation/deallocation directly using Fortran for 0-sized allocs. My original implementation was admittedly a little clumsy, I have simplified it now and have reverted the change to FIELD_RANKSUFF_MODULE and FIELD_BASIC_MODULE. Please take a look at it again when you have a few spare moments 😄