From 12c847e44a7a4f0c89b6347de945634a6bfd8897 Mon Sep 17 00:00:00 2001
From: Uwe Schulzweida <uwe.schulzweida@mpimet.mpg.de>
Date: Thu, 20 Feb 2025 20:33:50 +0100
Subject: [PATCH 1/6] Added compute_weights.c and compute_weights.h

---
 src/lib/yac/src/CMakeLists.txt | 4 ++++
 src/lib/yac/src/Makefile.am    | 4 ++--
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/lib/yac/src/CMakeLists.txt b/src/lib/yac/src/CMakeLists.txt
index 3485c8bf8..21ca118b6 100644
--- a/src/lib/yac/src/CMakeLists.txt
+++ b/src/lib/yac/src/CMakeLists.txt
@@ -7,6 +7,8 @@ list( APPEND yac_src_files
                check_overlap.c
                clipping.c
                clipping.h
+               compute_weights.c
+               compute_weights.h
                ensure_array_size.c
                ensure_array_size.h
                field_data.h
@@ -22,6 +24,8 @@ list( APPEND yac_src_files
                utils_core.c
                utils_core.h
                utils_common.h
+               yac_lapack_interface.c
+               yac_lapack_interface.h
                yac_types.h
                yac_version.h
 )
diff --git a/src/lib/yac/src/Makefile.am b/src/lib/yac/src/Makefile.am
index b78decdae..64e5234c7 100644
--- a/src/lib/yac/src/Makefile.am
+++ b/src/lib/yac/src/Makefile.am
@@ -10,6 +10,8 @@ libyac_la_SOURCES =                 \
                check_overlap.c      \
                clipping.c           \
                clipping.h           \
+               compute_weights.c    \
+               compute_weights.h    \
                ensure_array_size.c  \
                ensure_array_size.h  \
                field_data.h         \
@@ -25,8 +27,6 @@ libyac_la_SOURCES =                 \
                utils_core.c         \
                utils_core.h         \
                utils_common.h       \
-               compute_weights.c    \
-               compute_weights.h    \
                yac_lapack_interface.c \
                yac_lapack_interface.h \
                yac_types.h          \
-- 
GitLab


From 6c0d5031233fcb6e781130945d7fbf50b72eb745 Mon Sep 17 00:00:00 2001
From: Uwe Schulzweida <uwe.schulzweida@mpimet.mpg.de>
Date: Mon, 24 Feb 2025 10:21:30 +0100
Subject: [PATCH 2/6] levante: change to netcdf-c-4.9.2

---
 config/default | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/config/default b/config/default
index 30bc8e91d..9a1134d11 100755
--- a/config/default
+++ b/config/default
@@ -369,8 +369,10 @@ case "${HOSTNAME}" in
 #        NETCDFPATH=/sw/spack-levante/netcdf-c-4.8.1-qk24yp
 #        HDF5PATH=/sw/spack-levante/hdf5-1.12.1-akf2kp
     levante*)
-        NETCDFPATH=/sw/spack-levante/netcdf-c-4.8.1-qk24yp
-        HDF5PATH=/sw/spack-levante/hdf5-1.12.1-akf2kp
+        #NETCDFPATH=/sw/spack-levante/netcdf-c-4.8.1-qk24yp
+        #HDF5PATH=/sw/spack-levante/hdf5-1.12.1-akf2kp
+        NETCDFPATH=/sw/spack-levante/netcdf-c-4.9.2-ytsqvg
+        HDF5PATH=/sw/spack-levante/hdf5-1.14.0-h4ty2w
         UDUNITS2PATH=/sw/spack-levante/udunits-2.2.28-da6pla
         FFTW3PATH=/sw/spack-levante/fftw-3.3.10-fnfhvr
         ECCODESPATH=/sw/spack-levante/eccodes-2.32.5-ly6tko
-- 
GitLab


From 8e1a28a77c4a29874da531dba3c18b205f271d03 Mon Sep 17 00:00:00 2001
From: Uwe Schulzweida <uwe.schulzweida@mpimet.mpg.de>
Date: Mon, 24 Feb 2025 11:23:56 +0100
Subject: [PATCH 3/6] Added grid_reduced.cc

---
 src/CMakeLists.txt            |   2 +
 src/Makefile.am               |   7 +-
 src/mpim_grid/grid_reduced.cc | 181 ++++++++++++++++++++++++++++++++++
 src/mpim_grid/grid_reduced.h  |  14 +++
 src/mpim_grid/mpim_grid.cc    | 180 +--------------------------------
 src/mpim_grid/mpim_grid.h     |   3 -
 6 files changed, 203 insertions(+), 184 deletions(-)
 create mode 100644 src/mpim_grid/grid_reduced.cc
 create mode 100644 src/mpim_grid/grid_reduced.h

diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 2698ada55..d5772694e 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -303,6 +303,8 @@ list( APPEND cdolib_src_files
   mpim_grid/grid_options.h
   mpim_grid/grid_proj.cc
   mpim_grid/grid_proj.h
+  mpim_grid/grid_reduced.cc
+  mpim_grid/grid_reduced.h
   mpim_grid/grid_rot.cc
   mpim_grid/grid_rot.h
   remap_gradients.cc
diff --git a/src/Makefile.am b/src/Makefile.am
index d4ce11d01..96302eb9d 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -182,6 +182,9 @@ libcdo_la_SOURCES = after_dvtrans.cc      \
 				mpim_grid/grid_convert.h  \
 				mpim_grid/grid_proj.cc    \
 				mpim_grid/grid_proj.h     \
+				mpim_grid/grid_reduced.cc \
+				mpim_grid/grid_reduced.h  \
+				mpim_grid/grid_rot.h      \
 				mpim_grid/grid_rot.cc     \
 				mpim_grid/grid_rot.h      \
 				mpim_grid/grid_healpix.cc \
@@ -190,8 +193,8 @@ libcdo_la_SOURCES = after_dvtrans.cc      \
 				mpim_grid/gridreference.h \
 				mpim_grid/mpim_grid.cc    \
 				mpim_grid/mpim_grid.h     \
-				mpim_grid/grid_options.cc    \
-				mpim_grid/grid_options.h     \
+				mpim_grid/grid_options.cc \
+				mpim_grid/grid_options.h  \
 				mpmo.cc                   \
 				mpmo.h                    \
 				mpmo_color.cc             \
diff --git a/src/mpim_grid/grid_reduced.cc b/src/mpim_grid/grid_reduced.cc
new file mode 100644
index 000000000..f72e67905
--- /dev/null
+++ b/src/mpim_grid/grid_reduced.cc
@@ -0,0 +1,181 @@
+#include "grid_reduced.h"
+#include "cdo_output.h"
+
+/*
+ * grib_get_reduced_row: code from GRIB_API 1.10.4
+ *
+ * Description:
+ *   computes the number of points within the range lon_first->lon_last and the zero based indexes ilon_first,ilon_last
+ *   of the first and last point given the number of points along a parallel (pl)
+ *
+ */
+void
+grib_get_reduced_row(long pl, double lon_first, double lon_last, long *npoints, long *ilon_first, long *ilon_last)
+{
+  auto range = lon_last - lon_first;
+  if (range < 0.0)
+    {
+      range += 360.0;
+      lon_first -= 360.0;
+    }
+
+  // computing integer number of points and coordinates without using floating point resolution
+  *npoints = (range * pl) / 360.0 + 1;
+  *ilon_first = (lon_first * pl) / 360.0;
+  *ilon_last = (lon_last * pl) / 360.0;
+
+  auto irange = *ilon_last - *ilon_first + 1;
+
+  if (irange != *npoints)
+    {
+      if (irange > *npoints)
+        {
+          // checking if the first point is out of range
+          auto dlon_first = ((*ilon_first) * 360.0) / pl;
+          if (dlon_first < lon_first)
+            {
+              (*ilon_first)++;
+              irange--;
+            }
+
+          // checking if the last point is out of range
+          auto dlon_last = ((*ilon_last) * 360.0) / pl;
+          if (dlon_last > lon_last)
+            {
+              (*ilon_last)--;
+              irange--;
+            }
+        }
+      else
+        {
+          int ok = 0;
+          // checking if the point before the first is in the range
+          auto dlon_first = ((*ilon_first - 1) * 360.0) / pl;
+          if (dlon_first > lon_first)
+            {
+              (*ilon_first)--;
+              irange++;
+              ok = 1;
+            }
+
+          // checking if the point after the last is in the range
+          auto dlon_last = ((*ilon_last + 1) * 360.0) / pl;
+          if (dlon_last < lon_last)
+            {
+              (*ilon_last)++;
+              irange++;
+              ok = 1;
+            }
+
+          // if neither of the two are triggered then npoints is too large
+          if (!ok) (*npoints)--;
+        }
+
+      //   assert(*npoints==irange);
+    }
+  else
+    {
+      // checking if the first point is out of range
+      auto dlon_first = ((*ilon_first) * 360.0) / pl;
+      if (dlon_first < lon_first)
+        {
+          (*ilon_first)++;
+          (*ilon_last)++;
+        }
+    }
+
+  if (*ilon_first < 0) *ilon_first += pl;
+}
+
+int
+qu2reg_subarea(size_t gridsize, int np, double xfirst, double xlast, double *array, int *reducedPoints, int ny, double missval,
+               int *iret, int lmiss, int lperio, int lveggy)
+{
+  // sub area (longitudes)
+  long ilon_firstx;
+  long ilon_first, ilon_last;
+  int i, j;
+  long row_count;
+  int rlon;
+  int np4 = np * 4;
+  size_t size = 0;
+  int wlen;
+  int ii;
+
+  if (np <= 0) cdo_abort("Number of values between pole and equator missing!");
+
+  grib_get_reduced_row(np4, xfirst, xlast, &row_count, &ilon_firstx, &ilon_last);
+  int nx = row_count;
+  // printf("nx %d  %ld %ld lon1 %g lon2 %g\n", nx, ilon_firstx, ilon_last,
+  // (ilon_firstx*360.)/np4, (ilon_last*360.)/np4);
+
+  // int nwork = 0;
+  // for (j = 0; j < ny; ++j) nwork += reducedPoints[j];
+
+  double **pwork = (double **) malloc(ny * sizeof(double *));
+  double *work = (double *) malloc(ny * np4 * sizeof(double));
+  wlen = 0;
+  pwork[0] = work;
+  for (j = 1; j < ny; ++j)
+    {
+      wlen += reducedPoints[j - 1];
+      pwork[j] = work + wlen;
+    }
+  // printf(" ny, np4, nwork %d %d %d wlen %d\n", ny, np4, nwork, wlen);
+
+  for (j = 0; j < ny; ++j)
+    {
+      rlon = reducedPoints[j];
+      for (i = 0; i < rlon; ++i) pwork[j][i] = missval;
+    }
+
+  double *parray = array;
+  for (j = 0; j < ny; ++j)
+    {
+      rlon = reducedPoints[j];
+      row_count = 0;
+      grib_get_reduced_row(rlon, xfirst, xlast, &row_count, &ilon_first, &ilon_last);
+      // printf("j %d xfirst %g xlast %g reducedPoints %d %ld %ld %ld %g %g\n", j,
+      // xfirst, xlast, rlon, row_count, ilon_first, ilon_last,
+      // (ilon_first*360.)/rlon, (ilon_last*360.)/rlon);
+
+      for (i = ilon_first; i < (ilon_first + row_count); ++i)
+        {
+          ii = i;
+          if (ii >= rlon) ii -= rlon;
+          pwork[j][ii] = *parray;
+          parray++;
+        }
+      size += row_count;
+    }
+
+  if (gridsize != size) cdo_abort("gridsize1 inconsistent! (gridsize=%zu found=%zu)", gridsize, size);
+
+  qu2reg3_double(work, reducedPoints, ny, np4, missval, iret, lmiss, lperio, lveggy);
+
+  wlen = 0;
+  pwork[0] = work;
+  for (j = 1; j < ny; ++j)
+    {
+      wlen += np4;
+      pwork[j] = work + wlen;
+    }
+
+  // printf("nx, ilon_firstx %d %ld\n", nx, ilon_firstx);
+  parray = array;
+  for (j = 0; j < ny; ++j)
+    {
+      for (i = ilon_firstx; i < (ilon_firstx + nx); ++i)
+        {
+          ii = i;
+          if (ii >= np4) ii -= np4;
+          *parray = pwork[j][ii];
+          parray++;
+        }
+    }
+
+  free(work);
+  free(pwork);
+
+  return nx;
+}
diff --git a/src/mpim_grid/grid_reduced.h b/src/mpim_grid/grid_reduced.h
new file mode 100644
index 000000000..c366457a1
--- /dev/null
+++ b/src/mpim_grid/grid_reduced.h
@@ -0,0 +1,14 @@
+#ifndef GRID_REDUCED_H
+#define GRID_REDUCED_H
+
+#include "stdlib.h"
+
+extern "C" int qu2reg3_double(double *pfield, int *kpoint, int klat, int klon, double msval, int *kret, int omisng, int operio,
+                              int oveggy);
+
+void grib_get_reduced_row(long pl, double lon_first, double lon_last, long *npoints, long *ilon_first, long *ilon_last);
+
+int qu2reg_subarea(size_t gridsize, int np, double xfirst, double xlast, double *array, int *reducedPoints, int ny, double missval,
+                   int *iret, int lmiss, int lperio, int lveggy);
+
+#endif
diff --git a/src/mpim_grid/mpim_grid.cc b/src/mpim_grid/mpim_grid.cc
index 047b34ee8..7886eefd6 100644
--- a/src/mpim_grid/mpim_grid.cc
+++ b/src/mpim_grid/mpim_grid.cc
@@ -22,6 +22,7 @@
 #include "grid_rot.h"
 #include "grid_healpix.h"
 #include "gridreference.h"
+#include "grid_reduced.h"
 
 #include "compare.h"
 #include "cdo_output.h"
@@ -425,185 +426,6 @@ grid_gen_ybounds2D(size_t nx, size_t ny, const std::vector<double> &ybounds, std
     }
 }
 
-/*
- * grib_get_reduced_row: code from GRIB_API 1.10.4
- *
- * Description:
- *   computes the number of points within the range lon_first->lon_last and the zero based indexes ilon_first,ilon_last
- *   of the first and last point given the number of points along a parallel (pl)
- *
- */
-static void
-grib_get_reduced_row(long pl, double lon_first, double lon_last, long *npoints, long *ilon_first, long *ilon_last)
-{
-  auto range = lon_last - lon_first;
-  if (range < 0.0)
-    {
-      range += 360.0;
-      lon_first -= 360.0;
-    }
-
-  // computing integer number of points and coordinates without using floating point resolution
-  *npoints = (range * pl) / 360.0 + 1;
-  *ilon_first = (lon_first * pl) / 360.0;
-  *ilon_last = (lon_last * pl) / 360.0;
-
-  auto irange = *ilon_last - *ilon_first + 1;
-
-  if (irange != *npoints)
-    {
-      if (irange > *npoints)
-        {
-          // checking if the first point is out of range
-          auto dlon_first = ((*ilon_first) * 360.0) / pl;
-          if (dlon_first < lon_first)
-            {
-              (*ilon_first)++;
-              irange--;
-            }
-
-          // checking if the last point is out of range
-          auto dlon_last = ((*ilon_last) * 360.0) / pl;
-          if (dlon_last > lon_last)
-            {
-              (*ilon_last)--;
-              irange--;
-            }
-        }
-      else
-        {
-          int ok = 0;
-          // checking if the point before the first is in the range
-          auto dlon_first = ((*ilon_first - 1) * 360.0) / pl;
-          if (dlon_first > lon_first)
-            {
-              (*ilon_first)--;
-              irange++;
-              ok = 1;
-            }
-
-          // checking if the point after the last is in the range
-          auto dlon_last = ((*ilon_last + 1) * 360.0) / pl;
-          if (dlon_last < lon_last)
-            {
-              (*ilon_last)++;
-              irange++;
-              ok = 1;
-            }
-
-          // if neither of the two are triggered then npoints is too large
-          if (!ok) (*npoints)--;
-        }
-
-      //   assert(*npoints==irange);
-    }
-  else
-    {
-      // checking if the first point is out of range
-      auto dlon_first = ((*ilon_first) * 360.0) / pl;
-      if (dlon_first < lon_first)
-        {
-          (*ilon_first)++;
-          (*ilon_last)++;
-        }
-    }
-
-  if (*ilon_first < 0) *ilon_first += pl;
-}
-
-static int
-qu2reg_subarea(size_t gridsize, int np, double xfirst, double xlast, double *array, int *reducedPoints, int ny, double missval,
-               int *iret, int lmiss, int lperio, int lveggy)
-{
-  // sub area (longitudes)
-  long ilon_firstx;
-  long ilon_first, ilon_last;
-  int i, j;
-  long row_count;
-  int rlon;
-  int np4 = np * 4;
-  size_t size = 0;
-  int wlen;
-  int ii;
-
-  if (np <= 0) cdo_abort("Number of values between pole and equator missing!");
-
-  grib_get_reduced_row(np4, xfirst, xlast, &row_count, &ilon_firstx, &ilon_last);
-  int nx = row_count;
-  // printf("nx %d  %ld %ld lon1 %g lon2 %g\n", nx, ilon_firstx, ilon_last,
-  // (ilon_firstx*360.)/np4, (ilon_last*360.)/np4);
-
-  // int nwork = 0;
-  // for (j = 0; j < ny; ++j) nwork += reducedPoints[j];
-
-  double **pwork = (double **) malloc(ny * sizeof(double *));
-  double *work = (double *) malloc(ny * np4 * sizeof(double));
-  wlen = 0;
-  pwork[0] = work;
-  for (j = 1; j < ny; ++j)
-    {
-      wlen += reducedPoints[j - 1];
-      pwork[j] = work + wlen;
-    }
-  // printf(" ny, np4, nwork %d %d %d wlen %d\n", ny, np4, nwork, wlen);
-
-  for (j = 0; j < ny; ++j)
-    {
-      rlon = reducedPoints[j];
-      for (i = 0; i < rlon; ++i) pwork[j][i] = missval;
-    }
-
-  double *parray = array;
-  for (j = 0; j < ny; ++j)
-    {
-      rlon = reducedPoints[j];
-      row_count = 0;
-      grib_get_reduced_row(rlon, xfirst, xlast, &row_count, &ilon_first, &ilon_last);
-      // printf("j %d xfirst %g xlast %g reducedPoints %d %ld %ld %ld %g %g\n", j,
-      // xfirst, xlast, rlon, row_count, ilon_first, ilon_last,
-      // (ilon_first*360.)/rlon, (ilon_last*360.)/rlon);
-
-      for (i = ilon_first; i < (ilon_first + row_count); ++i)
-        {
-          ii = i;
-          if (ii >= rlon) ii -= rlon;
-          pwork[j][ii] = *parray;
-          parray++;
-        }
-      size += row_count;
-    }
-
-  if (gridsize != size) cdo_abort("gridsize1 inconsistent! (gridsize=%zu found=%zu)", gridsize, size);
-
-  qu2reg3_double(work, reducedPoints, ny, np4, missval, iret, lmiss, lperio, lveggy);
-
-  wlen = 0;
-  pwork[0] = work;
-  for (j = 1; j < ny; ++j)
-    {
-      wlen += np4;
-      pwork[j] = work + wlen;
-    }
-
-  // printf("nx, ilon_firstx %d %ld\n", nx, ilon_firstx);
-  parray = array;
-  for (j = 0; j < ny; ++j)
-    {
-      for (i = ilon_firstx; i < (ilon_firstx + nx); ++i)
-        {
-          ii = i;
-          if (ii >= np4) ii -= np4;
-          *parray = pwork[j][ii];
-          parray++;
-        }
-    }
-
-  free(work);
-  free(pwork);
-
-  return nx;
-}
-
 static void
 get_xfirst_and_xlast(int gridID, double &xfirst, double &xlast)
 {
diff --git a/src/mpim_grid/mpim_grid.h b/src/mpim_grid/mpim_grid.h
index c5534ec02..8a053c4b7 100644
--- a/src/mpim_grid/mpim_grid.h
+++ b/src/mpim_grid/mpim_grid.h
@@ -40,9 +40,6 @@ enum class NeedCorners
   IfAvail = 2
 };
 
-extern "C" int qu2reg3_double(double *pfield, int *kpoint, int klat, int klon, double msval, int *kret, int omisng, int operio,
-                              int oveggy);
-
 extern bool gridVerbose;
 
 static inline bool
-- 
GitLab


From 9537a5778c503aebff45ef022518ba812cb68936 Mon Sep 17 00:00:00 2001
From: Uwe Schulzweida <uwe.schulzweida@mpimet.mpg.de>
Date: Mon, 24 Feb 2025 13:47:00 +0100
Subject: [PATCH 4/6] cleanup

---
 src/Afterburner.cc            |  8 +++----
 src/CMOR.cc                   | 30 ++++++++++++------------
 src/CMOR_table.cc             |  2 +-
 src/EcaEtccdi.cc              |  2 +-
 src/Echam5ini.cc              | 44 +++++++++++++++++------------------
 src/Gradsdes.cc               |  4 ++--
 src/Healpix.cc                |  4 ++--
 src/Importbinary.cc           |  2 +-
 src/Importcmsaf.cc            | 24 +++++++++----------
 src/Lic.cc                    | 24 +++++++++----------
 src/Maggraph.cc               | 16 ++++++-------
 src/Magplot.cc                | 20 ++++++++--------
 src/Magvector.cc              |  2 +-
 src/Remapeta.cc               |  2 +-
 src/Selmulti.cc               | 38 +++++++++++++++---------------
 src/Seltime.cc                |  2 +-
 src/Setattribute.cc           |  2 +-
 src/Sinfo.cc                  |  2 +-
 src/after_namelist.cc         |  4 ++--
 src/afterburnerlib.cc         | 18 +++++++-------
 src/cdo_history.cc            | 11 ++++-----
 src/cdo_output.cc             |  2 +-
 src/cdo_settings.cc           |  2 +-
 src/cdo_zaxis.cc              |  4 ++--
 src/cfortran.h                |  2 +-
 src/cmortable_parser.cc       | 10 ++++----
 src/commandline.cc            |  2 +-
 src/datetime.cc               |  4 ++--
 src/dcw_reader.cc             | 26 +++++++++++----------
 src/expr.cc                   |  2 +-
 src/expr_fun.cc               |  2 +-
 src/fileStream.cc             |  2 +-
 src/grid_print.cc             | 10 ++++----
 src/grid_read.cc              | 14 +++++------
 src/griddes.cc                | 16 ++++++-------
 src/griddes_nc.cc             |  4 ++--
 src/magics_template_parser.cc | 11 +++++----
 src/param_conversion.cc       |  8 +++----
 src/pmlist.cc                 |  2 +-
 src/remap_scrip_io.cc         |  2 +-
 src/util_fileextensions.cc    |  4 ++--
 src/util_string.cc            |  2 +-
 src/util_wildcards.cc         |  2 +-
 src/zaxis_print.cc            |  6 ++---
 44 files changed, 200 insertions(+), 200 deletions(-)

diff --git a/src/Afterburner.cc b/src/Afterburner.cc
index 18a16d109..6f524e29f 100644
--- a/src/Afterburner.cc
+++ b/src/Afterburner.cc
@@ -105,7 +105,7 @@ FreeMean(struct Variable *vars)
   for (int code = 0; code < MaxCodes; ++code)
     if (vars[code].mean)
       {
-        free(vars[code].mean);
+        std::free(vars[code].mean);
         vars[code].mean = nullptr;
       }
 }
@@ -151,7 +151,7 @@ after_SwitchFile(AfterControl *globs)
 
   if (globs->Multi > 0)
     {
-      int i = strlen(ifile);
+      int i = std::strlen(ifile);
       if (i < 10)
         {
           fprintf(stderr, " Not a valid filename: %s \n", ifile);
@@ -1145,9 +1145,9 @@ after_parini(AfterControl &globs, struct Variable *vars)
   if (globs.Debug)
     {
       lprintf(stderr);
-      fprintf(stderr, "  Length of namelist:%4d bytes\n", (int) strlen(namelist));
+      fprintf(stderr, "  Length of namelist:%4d bytes\n", (int) std::strlen(namelist));
 
-      for (i = 0; i < (int) strlen(namelist); i += 60) fprintf(stderr, "  namelist[%02d]=%-60.60s\n", i, namelist + i);
+      for (i = 0; i < (int) std::strlen(namelist); i += 60) fprintf(stderr, "  namelist[%02d]=%-60.60s\n", i, namelist + i);
       lprintf(stderr);
     }
 
diff --git a/src/CMOR.cc b/src/CMOR.cc
index 8e68a8ffd..f29343ed2 100644
--- a/src/CMOR.cc
+++ b/src/CMOR.cc
@@ -678,7 +678,7 @@ addcharvar(const KeyValues *charvars, int vlistID, const std::string &key, struc
           std::strcat(ids, ",");
           std::strcat(ids, tempint);
         }
-      cdiDefAttTxt(vlistID, withnewcharaxis.inputKeys[0].varID, "merge_axis", (int) strlen(ids), ids);
+      cdiDefAttTxt(vlistID, withnewcharaxis.inputKeys[0].varID, "merge_axis", (int) std::strlen(ids), ids);
       return;
     }
   int ntsteps = vlistNtsteps(vlistID);
@@ -2114,7 +2114,7 @@ setup_dataset(KVList *kvl, CdoStreamID streamID, int *calendar, const std::strin
           notincluded,
           "The following attributes are not included in the global attributes list.\n          Reasons can be: 1. Attribute is "
           "an internal keyword 2. No valaue is available 3. CMOR creates the attribute itself:\n          ");
-      size_t inilen = strlen(notincluded);
+      size_t inilen = std::strlen(notincluded);
       size_t strlens = inilen;
       for (auto &kv : *kvl)
         {
@@ -2127,7 +2127,7 @@ setup_dataset(KVList *kvl, CdoStreamID streamID, int *calendar, const std::strin
             }
           else if (!keep_this_attribute(&kv, kaa_notneeded_general) || !keep_this_attribute(&kv, kaa_cmor2))
             {
-              strlens += (strlen(kv.key.c_str()) + 2);
+              strlens += (std::strlen(kv.key.c_str()) + 2);
               if (strlens < 2048)
                 {
                   std::strcat(notincluded, kv.key.c_str());
@@ -2175,7 +2175,7 @@ setup_dataset(KVList *kvl, CdoStreamID streamID, int *calendar, const std::strin
           {
             if (keep_this_attribute(&kv, kaa_notneeded_general))
               {
-                int linelen = strlen(kv.key.c_str()) + strlen(kv.values[0].c_str()) + 10;
+                int linelen = std::strlen(kv.key.c_str()) + std::strlen(kv.values[0].c_str()) + 10;
                 std::vector<char> line(linelen);
                 std::snprintf(line.data(), linelen, "\"%s\" : \"%s\",\n", kv.key.c_str(), kv.values[0].c_str());
                 fputs((const char *) line.data(), dataset_json);
@@ -2207,7 +2207,7 @@ setup_dataset(KVList *kvl, CdoStreamID streamID, int *calendar, const std::strin
             std::string tmp = kv_get_a_val(kvl, allneeded[i], "notSet");
             if (tmp.substr(0, 6) != "notSet")
               {
-                int linelen = strlen(allneeded[i].c_str()) + strlen(tmp.c_str()) + 10;
+                int linelen = std::strlen(allneeded[i].c_str()) + std::strlen(tmp.c_str()) + 10;
                 std::vector<char> line(linelen);
                 std::snprintf(line.data(), line.size(), "\"%s\" : \"%s\",\n", allneeded[i].c_str(), tmp.c_str());
                 fputs((const char *) line.data(), dataset_json);
@@ -3510,18 +3510,18 @@ register_projection(int *grid_ids, int projID, double *ycoord_vals, double *xcoo
   check_and_gen_bounds(projID, pynbounds, pylength, pycoord_vals, pycell_bounds, 0);
 
   char p_rll_cmor[CMOR_MAX_STRING];
-  int l_p_rll = strlen("grid_north_pole_longitude") + 1;
+  int l_p_rll = std::strlen("grid_north_pole_longitude") + 1;
   std::memcpy(p_rll_cmor,
               "grid_north_pole_latitude\0 "
               "grid_north_pole_longitude\0north_pole_grid_longitude\0",
               3 * l_p_rll);
 
   char u_rll_cmor[CMOR_MAX_STRING];
-  int l_u_rll = strlen("degrees_north") + 1;
+  int l_u_rll = std::strlen("degrees_north") + 1;
   std::memcpy(u_rll_cmor, "degrees_north\0degrees_east\0 degrees_east\0 ", 3 * l_u_rll);
 
   char p_lcc_cmor[CMOR_MAX_STRING];
-  int l_p_lcc = strlen("longitude_of_central_meridian") + 1;
+  int l_p_lcc = std::strlen("longitude_of_central_meridian") + 1;
   std::memcpy(p_lcc_cmor,
               "standard_parallel1\0           "
               "longitude_of_central_meridian\0latitude_of_projection_"
@@ -3551,7 +3551,7 @@ register_projection(int *grid_ids, int projID, double *ycoord_vals, double *xcoo
   cdiInqNatts(projID, CDI_GLOBAL, &natts);
 
   char p_ps_cmor[CMOR_MAX_STRING];
-  int l_p_ps = strlen("straight_vertical_longitude_from_pole") + 1;
+  int l_p_ps = std::strlen("straight_vertical_longitude_from_pole") + 1;
 
   if (projtype == CDI_PROJ_STERE)
     {
@@ -5654,7 +5654,7 @@ write_variables(KVList *kvl, CdoStreamID streamID, struct mapping vars[], int mi
                   char prelim[CMOR_MAX_STRING];
                   status = nc_get_att_text(ncid, NC_GLOBAL, "tracking_id", prelim);
                   std::string prefixCordex = "hdl:21.14103/";
-                  int lengthCombi = strlen(prelim) + strlen(prefixCordex);
+                  int lengthCombi = std::strlen(prelim) + std::strlen(prefixCordex);
                   std::string track;
                   std::snprintf(track, lengthCombi, "%s%s", prefixCordex, prelim);
                   status = nc_put_att_text(ncid, NC_GLOBAL, "tracking_id", (size_t) lengthCombi, (const char *) track);
@@ -5674,7 +5674,7 @@ write_variables(KVList *kvl, CdoStreamID streamID, struct mapping vars[], int mi
                             int vlistIDF = streamInqVlist(streamIDF);
                             std::string prelim = get_txtatt(vlistIDF, CDI_GLOBAL, "tracking_id");
                             std::string prefixCordex = strdup("21.14103/");
-                            size_t lengthCombi = (size_t) (strlen(prelim) + strlen(prefixCordex));
+                            size_t lengthCombi = (size_t) (std::strlen(prelim) + std::strlen(prefixCordex));
                             std::string track = (char *) std::malloc( lengthCombi *sizeof(char));
                             sprintf(track, "%s%s", prefixCordex, prelim);
                             cdiDefAttTxt(vlistIDF, CDI_GLOBAL, "tracking_id", lengthCombi, (const char *)track);
@@ -5768,7 +5768,7 @@ write_variables(KVList *kvl, CdoStreamID streamID, struct mapping vars[], int mi
                   std::memcpy(&timename[12], smon2, 2);
                 }
 
-              int cmdlen = 11 + kv_get_a_val(kvl, "cordexDir", "").length() + strlen(varname);
+              int cmdlen = 11 + kv_get_a_val(kvl, "cordexDir", "").length() + std::strlen(varname);
               std::vector<char> command1(cmdlen);
               std::snprintf(command1.data(), cmdlen, "mkdir -p %s/%s", kv_get_a_val(kvl, "cordexDir", "").c_str(), varname);
 
@@ -5782,7 +5782,7 @@ write_variables(KVList *kvl, CdoStreamID streamID, struct mapping vars[], int mi
               std::snprintf(cordex_file_name, CMOR_MAX_STRING, "%s/%s/%s_%s%s", kv_get_a_val(kvl, "cordexDir", "").c_str(), varname,
                             varname, kv_get_a_val(kvl, "cordexFileTem", "").c_str(), timename);
 
-              cmdlen = 5 + strlen(file_name) + strlen(cordex_file_name);
+              cmdlen = 5 + std::strlen(file_name) + std::strlen(cordex_file_name);
               std::vector<char> command2(cmdlen);
 
               std::snprintf(command2.data(), cmdlen, "mv %s %s", file_name, cordex_file_name);
@@ -5815,7 +5815,7 @@ write_variables(KVList *kvl, CdoStreamID streamID, struct mapping vars[], int mi
                   std::string startcmp = std::string(file_name);
                   int startpattern = 0, lastSlash = 0;
                   std::strcpy(chunkpath, file_name);
-                  int patternlength = strlen(oldmember);
+                  int patternlength = std::strlen(oldmember);
                   bool oldchunkcopied = false;
                   /* member is once in the path, once in the file name */
                   while (file_name[startpattern])
@@ -5825,7 +5825,7 @@ write_variables(KVList *kvl, CdoStreamID streamID, struct mapping vars[], int mi
                           if (!oldchunkcopied)
                             chunkpath[startpattern] = '\0';
                           else
-                            chunkpath[startpattern + strlen(newmember) - patternlength] = '\0';
+                            chunkpath[startpattern + std::strlen(newmember) - patternlength] = '\0';
                           startcmp.erase(0, patternlength);
                           startpattern += patternlength;
                           std::snprintf(newname, CDI_MAX_NAME, "%s%s%s", chunkpath, newmember, startcmp.c_str());
diff --git a/src/CMOR_table.cc b/src/CMOR_table.cc
index 94dff88d5..6709136eb 100644
--- a/src/CMOR_table.cc
+++ b/src/CMOR_table.cc
@@ -93,7 +93,7 @@ conv_cmor_table(const PMList &pmlist)
                     printf("  %-15s = \"%.*s\"\n", key.c_str(), vlen, ovalue);
                 }
 
-              free(ovalue);
+              std::free(ovalue);
             }
           if (hasmissval) printf("  %-15s = %g\n", "missing_value", missval);
           printf("/\n");
diff --git a/src/EcaEtccdi.cc b/src/EcaEtccdi.cc
index 38581e511..de32a8615 100644
--- a/src/EcaEtccdi.cc
+++ b/src/EcaEtccdi.cc
@@ -296,7 +296,7 @@ etccdi_op(ETCCDI_REQUEST &request)
       cdiDefKeyString(vlistID4, 0, CDI_KEY_NAME, request.name);
       cdiDefKeyString(vlistID4, 0, CDI_KEY_LONGNAME, request.longname);
       cdiDefKeyString(vlistID4, 0, CDI_KEY_UNITS, request.units);
-      cdiDefAttTxt(vlistID4, 0, "cell_methods", (int) strlen("time: maximum"), "time: maximum");
+      cdiDefAttTxt(vlistID4, 0, "cell_methods", (int) std::strlen("time: maximum"), "time: maximum");
     }
   else
     {
diff --git a/src/Echam5ini.cc b/src/Echam5ini.cc
index b4b937d05..312b0e77e 100644
--- a/src/Echam5ini.cc
+++ b/src/Echam5ini.cc
@@ -355,51 +355,51 @@ export_e5ml(const char *filename, const std::vector<VAR> &vars, int nvars, int v
 
   char atttext[1024];
   std::strcpy(atttext, "IEEE");
-  size_t attlen = strlen(atttext);
+  size_t attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "source_type", attlen, atttext));
 
   std::strcpy(atttext, cdo::command_line());
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "history", attlen, atttext));
 
   std::strcpy(atttext, username);
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "user", attlen, atttext));
 
   std::strcpy(atttext, timestr);
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "created", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_1", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_2", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_3", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_4", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_5", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_6", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_7", attlen, atttext));
 
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "label_8", attlen, atttext));
 
   nce(nc_put_att_int(nc_file_id, NC_GLOBAL, "fdate", NC_INT, 1, &vdate));
@@ -413,7 +413,7 @@ export_e5ml(const char *filename, const std::vector<VAR> &vars, int nvars, int v
   nce(nc_put_att_int(nc_file_id, NC_GLOBAL, "spherical_truncation_m", NC_INT, 1, &ntr));
   nce(nc_put_att_int(nc_file_id, NC_GLOBAL, "spherical_truncation_k", NC_INT, 1, &ntr));
 
-  nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "file_type", strlen(strfiletype_ml), strfiletype_ml));
+  nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "file_type", std::strlen(strfiletype_ml), strfiletype_ml));
 
   int lat_dimid;
   nce(nc_def_dim(nc_file_id, "lat", lat, &lat_dimid));
@@ -448,10 +448,10 @@ export_e5ml(const char *filename, const std::vector<VAR> &vars, int nvars, int v
   int nc_var_id;
   nce(nc_def_var(nc_file_id, "lat", NC_DOUBLE, 1, &lat_dimid, &nc_var_id));
   std::strcpy(atttext, "Gaussian latitude");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "long_name", attlen, atttext));
   std::strcpy(atttext, "degrees_N");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "units", attlen, atttext));
   nce(nc_enddef(nc_file_id));
   nce(nc_put_var_double(nc_file_id, nc_var_id, yvals));
@@ -459,10 +459,10 @@ export_e5ml(const char *filename, const std::vector<VAR> &vars, int nvars, int v
   nce(nc_redef(nc_file_id));
   nce(nc_def_var(nc_file_id, "lon", NC_DOUBLE, 1, &lon_dimid, &nc_var_id));
   std::strcpy(atttext, "longitude");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "long_name", attlen, atttext));
   std::strcpy(atttext, "degrees_E");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "units", attlen, atttext));
   nce(nc_enddef(nc_file_id));
   nce(nc_put_var_double(nc_file_id, nc_var_id, xvals));
@@ -479,10 +479,10 @@ export_e5ml(const char *filename, const std::vector<VAR> &vars, int nvars, int v
   nce(nc_redef(nc_file_id));
   nce(nc_def_var(nc_file_id, "vct_a", NC_DOUBLE, 1, &nvclev_dimid, &nc_var_id));
   std::strcpy(atttext, "vertical-coordinate parameter set A");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "long_name", attlen, atttext));
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "units", attlen, atttext));
   nce(nc_enddef(nc_file_id));
   nce(nc_put_var_double(nc_file_id, nc_var_id, vct));
@@ -490,10 +490,10 @@ export_e5ml(const char *filename, const std::vector<VAR> &vars, int nvars, int v
   nce(nc_redef(nc_file_id));
   nce(nc_def_var(nc_file_id, "vct_b", NC_DOUBLE, 1, &nvclev_dimid, &nc_var_id));
   std::strcpy(atttext, "vertical-coordinate parameter set B");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "long_name", attlen, atttext));
   std::strcpy(atttext, "");
-  attlen = strlen(atttext);
+  attlen = std::strlen(atttext);
   nce(nc_put_att_text(nc_file_id, nc_var_id, "units", attlen, atttext));
   nce(nc_enddef(nc_file_id));
   nce(nc_put_var_double(nc_file_id, nc_var_id, vct + nlevp1));
@@ -736,7 +736,7 @@ public:
     for (int iatt = 0; iatt < atts.natxt; ++iatt)
       {
         // printf("%s: %s\n", atts.atxtname[iatt], atts.atxtentry[iatt]);
-        cdiDefAttTxt(vlistID2, CDI_GLOBAL, atts.atxtname[iatt], (int) strlen(atts.atxtentry[iatt]) + 1, atts.atxtentry[iatt]);
+        cdiDefAttTxt(vlistID2, CDI_GLOBAL, atts.atxtname[iatt], (int) std::strlen(atts.atxtentry[iatt]) + 1, atts.atxtentry[iatt]);
       }
 
     auto taxisID = cdo_taxis_create(TAXIS_ABSOLUTE);
diff --git a/src/Gradsdes.cc b/src/Gradsdes.cc
index 6de128815..e0537c3d4 100644
--- a/src/Gradsdes.cc
+++ b/src/Gradsdes.cc
@@ -675,7 +675,7 @@ ctl_vars(FILE *gdp, int filetype, int vlistID, const VarList &varList, int nvars
           int nlev = zaxisInqSize(zaxisID);
 
           std::strcpy(varname, var.name.c_str());
-          int len = (int) strlen(varname);
+          int len = (int) std::strlen(varname);
           int i;
           for (i = 0; i < len; ++i)
             if (varname[i] == '-') break;
@@ -1103,7 +1103,7 @@ public:
     operatorID = cdo_operator_id();
 
     datfile = cdo_get_stream_name(0);
-    auto len = strlen(datfile);
+    auto len = std::strlen(datfile);
     ctlfile = new char[len + 10];
     std::strcpy(ctlfile, datfile);
 
diff --git a/src/Healpix.cc b/src/Healpix.cc
index 33ff26763..6efb23764 100644
--- a/src/Healpix.cc
+++ b/src/Healpix.cc
@@ -237,9 +237,9 @@ define_healpix_grid(size_t gridsize, int nside, HpOrder order)
   cdiDefKeyString(gridID, CDI_GLOBAL, CDI_KEY_DIMNAME, "cells");
   cdiDefKeyString(gridID, CDI_GLOBAL, CDI_KEY_GRIDMAP_VARNAME, projection);
   cdiDefKeyString(gridID, CDI_GLOBAL, CDI_KEY_GRIDMAP_NAME, projection);
-  cdiDefAttTxt(gridID, CDI_GLOBAL, "grid_mapping_name", (int) strlen(projection), projection);
+  cdiDefAttTxt(gridID, CDI_GLOBAL, "grid_mapping_name", (int) std::strlen(projection), projection);
   cdiDefAttInt(gridID, CDI_GLOBAL, "healpix_nside", CDI_DATATYPE_INT32, 1, &nside);
-  cdiDefAttTxt(gridID, CDI_GLOBAL, "healpix_order", (int) strlen(orderString), orderString);
+  cdiDefAttTxt(gridID, CDI_GLOBAL, "healpix_order", (int) std::strlen(orderString), orderString);
 
   return gridID;
 }
diff --git a/src/Importbinary.cc b/src/Importbinary.cc
index ca54ddd7f..05e3f7652 100644
--- a/src/Importbinary.cc
+++ b/src/Importbinary.cc
@@ -226,7 +226,7 @@ public:
         cdiDefKeyString(vlistID, varID, CDI_KEY_NAME, pvar->abbrv);
         {
           char *longname = pvar->varnm;
-          int len = (int) strlen(longname);
+          int len = (int) std::strlen(longname);
           if (longname[0] == '\'' && longname[len - 1] == '\'')
             {
               longname[len - 1] = 0;
diff --git a/src/Importcmsaf.cc b/src/Importcmsaf.cc
index d54d8e50c..1cde64f00 100644
--- a/src/Importcmsaf.cc
+++ b/src/Importcmsaf.cc
@@ -252,7 +252,7 @@ scan_pcs_def(char *pcs_def, char proj[128], double *a, double *lon0, double *lat
   *lat0 = 0;
 
   pcs[npcs++] = &pcs_def[0];
-  len = (int) strlen(pcs_def);
+  len = (int) std::strlen(pcs_def);
   for (int i = 0; i < len; ++i)
     if (pcs_def[i] == ',' && npcs < 64)
       {
@@ -347,7 +347,7 @@ read_geolocation(hid_t loc_id, int nx, int ny, int lprojtype)
   H5Tinsert(proj_tid, "Reference ellipsoid", HOFFSET(proj_t, ellipsoid), str_tid);
   H5Tinsert(proj_tid, "Projection parameter", HOFFSET(proj_t, parameter), fltarr_tid);
 
-  // if (projection_name) free(projection_name); failed with: pointer being freed was not allocated
+  // if (projection_name) std::free(projection_name); failed with: pointer being freed was not allocated
 
   grp_id = H5Gopen(loc_id, "Geolocation");
 
@@ -760,7 +760,7 @@ read_dataset(hid_t loc_id, const char *name, void *opdata)
       goto RETURN;
     }
 
-  len = (int) strlen(varname);
+  len = (int) std::strlen(varname);
   if (len > 0 && ((datasets_t *) opdata)->mergelevel)
     if (std::isdigit(varname[len - 1]) && std::memcmp(varname, "Data", 4) != 0)
       {
@@ -801,7 +801,7 @@ read_dataset(hid_t loc_id, const char *name, void *opdata)
           atype_size = H5Tget_size(atype);
           atype_class = H5Tget_class(atype);
 
-          len = strlen(attname);
+          len = std::strlen(attname);
           for (int k = 0; k < len; ++k) attname[k] = std::tolower(attname[k]);
 
           if (cdo_cmpstr(attname, "intercept") || cdo_cmpstr(attname, "offset"))
@@ -924,19 +924,19 @@ read_dataset(hid_t loc_id, const char *name, void *opdata)
           else if (cdo_cmpstr(attname, "description"))
             {
               H5Aread(attr, atype_mem, attstring);
-              if (((datasets_t *) opdata)->obj[nset].description) free(((datasets_t *) opdata)->obj[nset].description);
+              if (((datasets_t *) opdata)->obj[nset].description) std::free(((datasets_t *) opdata)->obj[nset].description);
               ((datasets_t *) opdata)->obj[nset].description = strdup(attstring);
             }
           else if (cdo_cmpstr(attname, "title"))
             {
               H5Aread(attr, atype_mem, attstring);
-              if (((datasets_t *) opdata)->obj[nset].title) free(((datasets_t *) opdata)->obj[nset].title);
+              if (((datasets_t *) opdata)->obj[nset].title) std::free(((datasets_t *) opdata)->obj[nset].title);
               ((datasets_t *) opdata)->obj[nset].title = strdup(attstring);
             }
           else if (cdo_cmpstr(attname, "time"))
             {
               H5Aread(attr, atype_mem, attstring);
-              if (((datasets_t *) opdata)->obj[nset].time) free(((datasets_t *) opdata)->obj[nset].time);
+              if (((datasets_t *) opdata)->obj[nset].time) std::free(((datasets_t *) opdata)->obj[nset].time);
               ((datasets_t *) opdata)->obj[nset].time = strdup(attstring);
             }
           else if (cdo_cmpstr(attname, "unit"))
@@ -952,7 +952,7 @@ read_dataset(hid_t loc_id, const char *name, void *opdata)
 
       int offset = gridsize * (nz - 1);
       double *array = ((datasets_t *) opdata)->obj[nset].array;
-      array = (double *) realloc(array, gridsize * nz * nt * sizeof(double));
+      array = (double *) std::realloc(array, gridsize * nz * nt * sizeof(double));
       ((datasets_t *) opdata)->obj[nset].array = array;
       array = array + offset;
 
@@ -1166,7 +1166,7 @@ get_global_att(hid_t file_id, const char *obj_path, int vlistID)
       H5Aget_name(attr, sizeof(attname), attname);
 
       /* remove illegal characters */
-      for (pos = 0; pos < (int) strlen(attname); ++pos)
+      for (pos = 0; pos < (int) std::strlen(attname); ++pos)
         if (attname[pos] == '&') attname[pos] = '_';
 
       atype_mem = H5Tget_native_type(atype, H5T_DIR_ASCEND);
@@ -1174,7 +1174,7 @@ get_global_att(hid_t file_id, const char *obj_path, int vlistID)
       if (type_class == H5T_STRING)
         {
           H5Aread(attr, atype_mem, attstring);
-          cdiDefAttTxt(vlistID, CDI_GLOBAL, attname, (int) strlen(attstring), attstring);
+          cdiDefAttTxt(vlistID, CDI_GLOBAL, attname, (int) std::strlen(attstring), attstring);
         }
       else if (type_class == H5T_INTEGER)
         {
@@ -1387,7 +1387,7 @@ public:
         if (dsets.obj[ivar].description) cdiDefKeyString(vlistID, varID, CDI_KEY_LONGNAME, dsets.obj[ivar].description);
         if (dsets.obj[ivar].units) cdiDefKeyString(vlistID, varID, CDI_KEY_UNITS, dsets.obj[ivar].units);
         if (dsets.obj[ivar].title)
-          cdiDefAttTxt(vlistID, varID, "title", (int) strlen(dsets.obj[ivar].title), dsets.obj[ivar].title);
+          cdiDefAttTxt(vlistID, varID, "title", (int) std::strlen(dsets.obj[ivar].title), dsets.obj[ivar].title);
 
         vlistDefVarDatatype(vlistID, varID, dsets.obj[ivar].dtype);
         if (dsets.obj[ivar].haveMissvals) vlistDefVarMissval(vlistID, varID, dsets.obj[ivar].missval);
@@ -1458,7 +1458,7 @@ public:
     cdo_stream_close(streamID);
     vlistDestroy(vlistID);
 
-    for (ivar = 0; ivar < dsets.numSets; ++ivar) free(dsets.obj[ivar].array);
+    for (ivar = 0; ivar < dsets.numSets; ++ivar) std::free(dsets.obj[ivar].array);
 
 #endif
   }
diff --git a/src/Lic.cc b/src/Lic.cc
index 11124f3c5..030f37912 100644
--- a/src/Lic.cc
+++ b/src/Lic.cc
@@ -209,7 +209,7 @@ WriteImage2PNG(int width, int height, unsigned char *pImage, float *mag, const c
   png_write_info(png_ptr, info_ptr);
 
   // Allocate memory for one row (3 bytes per pixel - RGB)
-  row = (png_bytep) malloc(3 * width * sizeof(png_byte));
+  row = (png_bytep) std::malloc(3 * width * sizeof(png_byte));
 
   // Write image data
   for (int y = 0; y < height; y++)
@@ -225,7 +225,7 @@ finalise:
   if (fp != nullptr) std::fclose(fp);
   if (info_ptr != nullptr) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
   if (png_ptr != nullptr) png_destroy_write_struct(&png_ptr, (png_infopp) nullptr);
-  if (row != nullptr) free(row);
+  if (row != nullptr) std::free(row);
 
   return code;
 }
@@ -368,12 +368,12 @@ FlowImagingLIC(int n_xres, int n_yres, float *pVectr, unsigned char *pNoise, uns
 static void
 lic1(const char *obasename, int num, int n_xres, int n_yres, float *pVectr)
 {
-  float *p_LUT0 = (float *) malloc(sizeof(float) * DISCRETE_FILTER_SIZE);
-  float *p_LUT1 = (float *) malloc(sizeof(float) * DISCRETE_FILTER_SIZE);
-  unsigned char *pNoise = (unsigned char *) malloc(sizeof(unsigned char) * n_xres * n_yres);
-  unsigned char *pImage = (unsigned char *) malloc(sizeof(unsigned char) * n_xres * n_yres);
+  float *p_LUT0 = (float *) std::malloc(sizeof(float) * DISCRETE_FILTER_SIZE);
+  float *p_LUT1 = (float *) std::malloc(sizeof(float) * DISCRETE_FILTER_SIZE);
+  unsigned char *pNoise = (unsigned char *) std::malloc(sizeof(unsigned char) * n_xres * n_yres);
+  unsigned char *pImage = (unsigned char *) std::malloc(sizeof(unsigned char) * n_xres * n_yres);
 
-  float *mag = (float *) malloc(n_xres * n_yres * sizeof(float));
+  float *mag = (float *) std::malloc(n_xres * n_yres * sizeof(float));
   int n = n_xres * n_yres;
 
 #ifdef _OPENMP
@@ -409,11 +409,11 @@ lic1(const char *obasename, int num, int n_xres, int n_yres, float *pVectr)
   cdo_warning("PNG support not compiled in!");
 #endif
 
-  free(p_LUT0);
-  free(p_LUT1);
-  free(pNoise);
-  free(pImage);
-  free(mag);
+  std::free(p_LUT0);
+  std::free(p_LUT1);
+  std::free(pNoise);
+  std::free(pImage);
+  std::free(mag);
 }
 
 class Lic : public Process
diff --git a/src/Maggraph.cc b/src/Maggraph.cc
index a24dc5227..5d3c16aa3 100644
--- a/src/Maggraph.cc
+++ b/src/Maggraph.cc
@@ -269,7 +269,7 @@ maggraph(const char *plotfile, const std::string &varname, const std::string &va
         }
     }
 
-  char ***date_time_str = (char ***) malloc(nfiles * sizeof(char **));
+  char ***date_time_str = (char ***) std::malloc(nfiles * sizeof(char **));
 
   std::vector<double> date_time;
   std::vector<double> mean_val, std_dev_val;
@@ -278,7 +278,7 @@ maggraph(const char *plotfile, const std::string &varname, const std::string &va
   if (stat)
     {
       // if all files are of same number of steps, only one date_time_str array is being used
-      date_time_str[0] = (char **) malloc(ntime_steps * sizeof(char *));
+      date_time_str[0] = (char **) std::malloc(ntime_steps * sizeof(char *));
 
       date_time.resize(ntime_steps);
       mean_val.resize(ntime_steps);
@@ -289,7 +289,7 @@ maggraph(const char *plotfile, const std::string &varname, const std::string &va
       for (tsID = 0; tsID < ntime_steps; ++tsID)
         {
           date_time[tsID] = tsID + 1;
-          date_time_str[0][tsID] = (char *) malloc(256);
+          date_time_str[0][tsID] = (char *) std::malloc(256);
           std::snprintf(date_time_str[0][tsID], 256, "%s", datetime_to_string(vDateTimes[0][tsID]).c_str());
           mean_val[tsID] = 0.;
           std_dev_val[tsID] = 0.;
@@ -366,13 +366,13 @@ maggraph(const char *plotfile, const std::string &varname, const std::string &va
         {
           if (DBG) fprintf(stderr, "FILE  %ld\n", fileID);
           date_time.resize(nts[fileID]);
-          date_time_str[fileID] = (char **) malloc(nts[fileID] * sizeof(char *));
+          date_time_str[fileID] = (char **) std::malloc(nts[fileID] * sizeof(char *));
 
           for (tsID = 0; tsID < nts[fileID]; ++tsID)
             {
               date_time[tsID] = tsID + 1;
 
-              date_time_str[fileID][tsID] = (char *) malloc(256);
+              date_time_str[fileID][tsID] = (char *) std::malloc(256);
               std::snprintf(date_time_str[fileID][tsID], 256, "%s", datetime_to_string(vDateTimes[fileID][tsID]).c_str());
               if (DBG && (tsID == 0 || tsID == nts[fileID] - 1)) fprintf(stderr, "%s\n", date_time_str[fileID][tsID]);
 
@@ -602,7 +602,7 @@ maggraph(const char *plotfile, const std::string &varname, const std::string &va
     }
 
   char *lines[1];
-  lines[0] = (char *) malloc(1024);
+  lines[0] = (char *) std::malloc(1024);
   // To be obtained from Meta Data
   // std::snprintf(lines[0], 1024, "%s","ExpID : " );
   // std::snprintf(lines[0], 1024, "%sxxxx  Variable : %s[%s]",lines[0], varname.c_str(), varunits.c_str() );
@@ -624,11 +624,11 @@ maggraph(const char *plotfile, const std::string &varname, const std::string &va
   mag_setc("text_justification", "left");
   mag_text();
 
-  free(date_time_str);
+  std::free(date_time_str);
 
   if (DBG) fprintf(stderr, "lines=%s\n", lines[0]);
 
-  free(lines[0]);
+  std::free(lines[0]);
 }
 
 static void
diff --git a/src/Magplot.cc b/src/Magplot.cc
index f0bc32737..a5978d6cf 100644
--- a/src/Magplot.cc
+++ b/src/Magplot.cc
@@ -202,7 +202,7 @@ checkcolour(char *colour_in)
           return 1;
         }
 
-      int n = strlen(colour_in);
+      int n = std::strlen(colour_in);
 
       if (DBG) fprintf(stdout, "  count %d  original colour %s RGB %d\n", n, colour_in, isRGB);
 
@@ -214,7 +214,7 @@ checkcolour(char *colour_in)
         }
       temp[i - 4] = '\0';
 
-      if (DBG) fprintf(stdout, "  count %d  modified color %s \n", (int) strlen(temp), temp);
+      if (DBG) fprintf(stdout, "  count %d  modified color %s \n", (int) std::strlen(temp), temp);
 
       const auto splitStrings = split_string(temp, ";");
 
@@ -277,12 +277,12 @@ ReadColourTable(char *filepath)
     }
 
   USR_COLOUR_COUNT = 0;
-  USR_COLOUR_TABLE = (char **) malloc(num_colors * sizeof(char *));
-  char **temp_table = (char **) malloc(num_colors * sizeof(char *));
+  USR_COLOUR_TABLE = (char **) std::malloc(num_colors * sizeof(char *));
+  char **temp_table = (char **) std::malloc(num_colors * sizeof(char *));
 
   for (int i = 0; i < num_colors; ++i)
     {
-      temp_table[i] = (char *) malloc(256 * sizeof(char));
+      temp_table[i] = (char *) std::malloc(256 * sizeof(char));
       std::fscanf(fp, "%s", temp_table[i]);
       if (DBG) fprintf(stdout, "%s\n", temp_table[i]);
     }
@@ -311,8 +311,8 @@ ReadColourTable(char *filepath)
 
   if (USR_COLOUR_COUNT < num_colors) cdo_warning(" Discarding improper format colours and continuing!");
 
-  for (int i = 0; i < num_colors; ++i) free(temp_table[i]);
-  free(temp_table);
+  for (int i = 0; i < num_colors; ++i) std::free(temp_table[i]);
+  std::free(temp_table);
 
   return 0;
 }
@@ -626,7 +626,7 @@ public:
                             if (syntax == true)
                               {
                                 NUM_LEVELS = (int) splitStrings2.size();
-                                LEV_LIST = (double *) malloc(NUM_LEVELS * sizeof(double));
+                                LEV_LIST = (double *) std::malloc(NUM_LEVELS * sizeof(double));
                                 for (int k = 0; k < NUM_LEVELS; ++k) LEV_LIST[k] = std::stof(splitStrings2[k]);
                               }
                           }
@@ -634,7 +634,7 @@ public:
                   } /*** if(key == params[j])  ***/
               }     /*** Loop over param count ***/
 
-            // if (value) free(value); // value is use e.g. for DEVICE
+            // if (value) std::free(value); // value is use e.g. for DEVICE
           } /*** (splitStrings.size() > 1) ***/
         else { syntax = false; }
 
@@ -994,7 +994,7 @@ public:
     mag_setc("text_justification", "left");
     mag_text();
 
-    if (LEV_LIST) free(LEV_LIST);
+    if (LEV_LIST) std::free(LEV_LIST);
   }
 
 #endif
diff --git a/src/Magvector.cc b/src/Magvector.cc
index cf0b315f9..c1d8b63ec 100644
--- a/src/Magvector.cc
+++ b/src/Magvector.cc
@@ -188,7 +188,7 @@ magvector(const char *plotfile, long nlon, long nlat, Varray<double> &grid_cente
     mag_text();
   }
 
-  free(titlename);
+  std::free(titlename);
 }
 
 void
diff --git a/src/Remapeta.cc b/src/Remapeta.cc
index 479ff159a..46b8b3097 100644
--- a/src/Remapeta.cc
+++ b/src/Remapeta.cc
@@ -118,7 +118,7 @@ vct_from_file(const std::string &filename)
 
       vct[i + maxvct / 2] = strtod(pline, &pline);
 
-      free(lineCpy);
+      std::free(lineCpy);
 
       i++;
     }
diff --git a/src/Selmulti.cc b/src/Selmulti.cc
index 34d5b93b7..481baccab 100644
--- a/src/Selmulti.cc
+++ b/src/Selmulti.cc
@@ -534,7 +534,7 @@ public:
 TUPLEREC *
 TUPLERECNew()
 {
-  TUPLEREC *tpl = (TUPLEREC *) malloc(sizeof(TUPLEREC));
+  TUPLEREC *tpl = (TUPLEREC *) std::malloc(sizeof(TUPLEREC));
 
   tpl->ncodes = 0;
 
@@ -654,8 +654,8 @@ strContains(char *str, const char *substr)
 
   str = removeSpaces(str);
 
-  size_t lensub = strlen(substr);
-  size_t lenstr = strlen(str);
+  size_t lensub = std::strlen(substr);
+  size_t lenstr = std::strlen(str);
 
   if (lensub > lenstr)
     {
@@ -693,7 +693,7 @@ findParamEnd(char *str)
       return ptrEnding;
     }
   Debug(cdoDebugExt >= 100, " ptrEnding=end-of-string");
-  size_t lenstr = strlen(str);
+  size_t lenstr = std::strlen(str);
   ptrEnding = str + lenstr;
   ptrEnding = removeSpaces(ptrEnding);
   return ptrEnding;
@@ -716,7 +716,7 @@ findTupleEnd(char *str)
       return ptrEnding;
     }
   Debug(cdoDebugExt >= 100, " findTupleEnd=end-of-string");
-  size_t lenstr = strlen(str);
+  size_t lenstr = std::strlen(str);
   ptrEnding = str + lenstr;
   ptrEnding = removeSpaces(ptrEnding);
   return ptrEnding;
@@ -739,7 +739,7 @@ readlineForParsing(std::ifstream &gfile, char *strToParsePtr, char *line)
     {
       if (cdoDebugExt >= 30) cdo_print("%s(): Parsing selection string:  %s", __func__, strToParsePtr);
       char *tpEnd = nullptr;
-      if (strlen(strToParsePtr) > 0) tpEnd = findTupleEnd(strToParsePtr);
+      if (std::strlen(strToParsePtr) > 0) tpEnd = findTupleEnd(strToParsePtr);
       if (tpEnd == nullptr)
         {
           Debug(cdoDebugExt >= 100, "%s(): End of selection string reached.", __func__);
@@ -748,7 +748,7 @@ readlineForParsing(std::ifstream &gfile, char *strToParsePtr, char *line)
       else
         {
           tpEnd[0] = 0;
-          if (strlen(strToParsePtr) <= MAX_LINE_LEN) std::strcpy(line, strToParsePtr);
+          if (std::strlen(strToParsePtr) <= MAX_LINE_LEN) std::strcpy(line, strToParsePtr);
           Debug(cdoDebugExt >= 100, "%s(): Current selection line=%s", __func__, line);
           strToParsePtr = tpEnd + 1;
           return strToParsePtr;
@@ -789,7 +789,7 @@ multiSelectionParser(const char *filenameOrString)
       std::strncpy(strToParse, filenameOrString, MAX_LINE_LEN - 1);
       strToParsePtr = &strToParse[0];
       if (strToParsePtr[0] == '{') strToParsePtr++;
-      int strLn = strlen(strToParsePtr);
+      int strLn = std::strlen(strToParsePtr);
       if (strToParsePtr[strLn - 1] == '}') strToParsePtr[strLn - 1] = 0;
       Debug(cdoDebugExt, " Parsing selection string:  %s", strToParsePtr);
     }
@@ -837,7 +837,7 @@ multiSelectionParser(const char *filenameOrString)
           tuplerec->sel_or_del_or_change = selectionRec;
           push_backSelTuple(tuplerec);
           // SELECT, PARAMETER=11/17, LEVTYPE=105, LEVEL=2
-          while ((pline != nullptr) && (strlen(pline) != 0))
+          while ((pline != nullptr) && (std::strlen(pline) != 0))
             {
               Debug(cdoDebugExt >= 100, "pline='%s'", pline);
               strpos = strContains(pline, "PARAMETER=");
@@ -848,7 +848,7 @@ multiSelectionParser(const char *filenameOrString)
                   pline = removeSpaces(pline);
                   parEnd = findParamEnd(pline);
                   if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                  while ((pline != parEnd) && (strlen(pline) > 0))
+                  while ((pline != parEnd) && (std::strlen(pline) > 0))
                     {
                       pline = removeSpaces(pline);
                       if (pline[0] == '*')
@@ -873,7 +873,7 @@ multiSelectionParser(const char *filenameOrString)
                   pline = removeSpaces(pline);
                   parEnd = findParamEnd(pline);
                   if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                  while ((pline != parEnd) && (strlen(pline) > 0))
+                  while ((pline != parEnd) && (std::strlen(pline) > 0))
                     {
                       pline = removeSpaces(pline);
                       if (pline[0] == '*')
@@ -907,7 +907,7 @@ multiSelectionParser(const char *filenameOrString)
                   pline = removeSpaces(pline);
                   parEnd = findParamEnd(pline);
                   if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                  while ((pline != parEnd) && (strlen(pline) > 0))
+                  while ((pline != parEnd) && (std::strlen(pline) > 0))
                     {
                       pline = removeSpaces(pline);
                       val = (pline[0] == '*') ? -1 : atoi(pline);
@@ -930,7 +930,7 @@ multiSelectionParser(const char *filenameOrString)
                   pline = removeSpaces(pline);
                   parEnd = findParamEnd(pline);
                   if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                  while ((pline != parEnd) && (strlen(pline) > 0))
+                  while ((pline != parEnd) && (std::strlen(pline) > 0))
                     {
                       pline = removeSpaces(pline);
                       floatval = atof(pline);
@@ -953,7 +953,7 @@ multiSelectionParser(const char *filenameOrString)
                   pline = removeSpaces(pline);
                   parEnd = findParamEnd(pline);
                   if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                  while ((pline != parEnd) && (strlen(pline) > 0))
+                  while ((pline != parEnd) && (std::strlen(pline) > 0))
                     {
                       pline = removeSpaces(pline);
                       floatval = atof(pline);
@@ -1005,7 +1005,7 @@ multiSelectionParser(const char *filenameOrString)
           tuplerec->sel_or_del_or_change = selectionRec;
           push_backSelTuple(tuplerec);
           // (33/34; 105; 10)
-          while ((pline != nullptr) && (strlen(pline) != 0) && (pline[0] != ')'))
+          while ((pline != nullptr) && (std::strlen(pline) != 0) && (pline[0] != ')'))
             {
               Debug(cdoDebugExt >= 100, "[1]: pline='%s'", pline);
               // 1st is code
@@ -1013,7 +1013,7 @@ multiSelectionParser(const char *filenameOrString)
                 pline = removeSpaces(pline);
                 parEnd = findParamEnd(pline);
                 if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                while ((pline != parEnd) && (strlen(pline) > 0))
+                while ((pline != parEnd) && (std::strlen(pline) > 0))
                   {
                     pline = removeSpaces(pline);
                     if (pline[0] == '*')
@@ -1040,7 +1040,7 @@ multiSelectionParser(const char *filenameOrString)
                 pline = removeSpaces(pline);
                 parEnd = findParamEnd(pline);
                 if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                while ((pline != parEnd) && (strlen(pline) > 0))
+                while ((pline != parEnd) && (std::strlen(pline) > 0))
                   {
                     pline = removeSpaces(pline);
                     val = (pline[0] == '*') ? -1 : atoi(pline);
@@ -1074,7 +1074,7 @@ multiSelectionParser(const char *filenameOrString)
                 pline = removeSpaces(pline);
                 parEnd = findParamEnd(pline);
                 if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                while ((pline != parEnd) && (strlen(pline) > 0))
+                while ((pline != parEnd) && (std::strlen(pline) > 0))
                   {
                     pline = removeSpaces(pline);
                     val = (pline[0] == '*') ? -1 : atoi(pline);
@@ -1147,7 +1147,7 @@ multiSelectionParser(const char *filenameOrString)
                   }  // changemulti specification
                 parEnd = findParamEnd(pline);
                 if ((!parEnd) && (!pline)) Debug(cdoDebugExt >= 100, "strpos=%s; parEnd=%s ... pline=%s", strpos, parEnd, pline);
-                while ((pline != parEnd) && (strlen(pline) > 0))
+                while ((pline != parEnd) && (std::strlen(pline) > 0))
                   {
                     pline = removeSpaces(pline);
                     val = (pline[0] == '*') ? -1 : atoi(pline);
diff --git a/src/Seltime.cc b/src/Seltime.cc
index 8062f31ee..90d23ad1f 100644
--- a/src/Seltime.cc
+++ b/src/Seltime.cc
@@ -293,7 +293,7 @@ public:
         for (int i = 0; i < numSel; ++i)
           {
             auto currentArgument = cdo_operator_argv(i).c_str();
-            if (strchr(currentArgument, ':'))
+            if (std::strchr(currentArgument, ':'))
               {
                 int hour = 0, minute = 0, second = 0;
                 std::sscanf(currentArgument, "%d:%d:%d", &hour, &minute, &second);
diff --git a/src/Setattribute.cc b/src/Setattribute.cc
index 792937039..d545bfb3c 100644
--- a/src/Setattribute.cc
+++ b/src/Setattribute.cc
@@ -21,7 +21,7 @@ get_datatype(char *buffer)
 {
   int dtype = -1;
 
-  auto slen = strlen(buffer);
+  auto slen = std::strlen(buffer);
   if (slen >= 3 && buffer[slen - 2] == ':')
     {
       if (slen >= 4 && buffer[slen - 3] == '\\')
diff --git a/src/Sinfo.cc b/src/Sinfo.cc
index 877c933a2..ea92aab7a 100644
--- a/src/Sinfo.cc
+++ b/src/Sinfo.cc
@@ -95,7 +95,7 @@ static void
 limit_string_length(char *string, size_t maxlen)
 {
   string[maxlen - 1] = 0;
-  auto len = strlen(string);
+  auto len = std::strlen(string);
   if (len > 10)
     {
       for (size_t i = 3; i < len; ++i)
diff --git a/src/after_namelist.cc b/src/after_namelist.cc
index daa39a093..4c722a081 100644
--- a/src/after_namelist.cc
+++ b/src/after_namelist.cc
@@ -10,8 +10,8 @@
 static char *
 amatch(char *msr, const char *sub)
 {
-  int nm = static_cast<int>(strlen(msr));
-  int ns = static_cast<int>(strlen(sub));
+  int nm = static_cast<int>(std::strlen(msr));
+  int ns = static_cast<int>(std::strlen(sub));
 
   for (int i = 0; i < nm - ns; ++i)
     if (std::strncmp(msr + i, sub, ns) == 0) return (msr + i + ns);
diff --git a/src/afterburnerlib.cc b/src/afterburnerlib.cc
index 22da4b83e..e690b67f1 100644
--- a/src/afterburnerlib.cc
+++ b/src/afterburnerlib.cc
@@ -27,7 +27,7 @@ FreeMemory(T &ptr)
 {
   if (ptr)
     {
-      free(ptr);
+      std::free(ptr);
       ptr = nullptr;
     }
 }
@@ -70,7 +70,7 @@ alloc_dp(int words, const char *array_name)
 
   if (words > 0)
     {
-      result = (double *) malloc(words * sizeof(double));
+      result = (double *) std::malloc(words * sizeof(double));
       if (result == nullptr) cdo_sys_error(array_name, "No Memory!");
     }
 
@@ -186,8 +186,8 @@ after_GP2FC(double *gp, double *fc, long nlat, long nlon, long nlev, long nfc)
 
   if (ifax[9] != nlon)
     {
-      if (trig) free(trig);
-      trig = (double *) malloc(nlon * sizeof(double));
+      if (trig) std::free(trig);
+      trig = (double *) std::malloc(nlon * sizeof(double));
       int status = fft_set(trig, ifax, nlon);
       if (status < 0) exit(1);
     }
@@ -203,8 +203,8 @@ after_FC2GP(double *fc, double *gp, long nlat, long nlon, long nlev, long nfc)
 
   if (ifax[9] != nlon)
     {
-      if (trig) free(trig);
-      trig = (double *) malloc(nlon * sizeof(double));
+      if (trig) std::free(trig);
+      trig = (double *) std::malloc(nlon * sizeof(double));
       int status = fft_set(trig, ifax, nlon);
       if (status < 0) exit(1);
     }
@@ -1102,7 +1102,7 @@ after_EchamCompGP(const AfterControl &globs, struct Variable *vars)
       auto &geopotheight = vars[GEOPOTHEIGHT];
       geopotheight.hlev = globs.NumLevel + 1;
       geopotheight.sfit = true;
-      geopotheight.hybrid = (double *) realloc(geopotheight.hybrid, (globs.Dim3GP + globs.DimGP) * sizeof(double));
+      geopotheight.hybrid = (double *) std::realloc(geopotheight.hybrid, (globs.Dim3GP + globs.DimGP) * sizeof(double));
       array_copy(globs.DimGP, globs.orography.data(), geopotheight.hybrid + globs.Dim3GP);
       for (int i = 0; i < globs.DimGP; ++i) geopotheight.hybrid[globs.Dim3GP + i] /= PlanetGrav;
     }
@@ -2285,7 +2285,7 @@ after_AnalysisAddField(const AfterControl *globs, struct Variable *vars, int cod
         {
           if (vars[code].samp == nullptr)
             {
-              vars[code].samp = (int *) malloc(dataSize * sizeof(int));
+              vars[code].samp = (int *) std::malloc(dataSize * sizeof(int));
               for (size_t i = 0; i < dataSize; ++i) vars[code].samp[i] = globs->MeanCount0;
             }
 
@@ -2360,7 +2360,7 @@ after_EchamAddField(const AfterControl *globs, struct Variable *vars, int code,
         {
           if (vars[code].samp == nullptr)
             {
-              vars[code].samp = (int *) malloc(dataSize * sizeof(int));
+              vars[code].samp = (int *) std::malloc(dataSize * sizeof(int));
               for (size_t i = 0; i < dataSize; ++i) vars[code].samp[i] = globs->MeanCount0;
             }
 
diff --git a/src/cdo_history.cc b/src/cdo_history.cc
index 10651f022..e03cd6661 100644
--- a/src/cdo_history.cc
+++ b/src/cdo_history.cc
@@ -7,7 +7,7 @@
 
 #include <vector>
 #include <string>
-#include <string.h>
+#include <cstring>
 #include <time.h>
 
 #include <cdi.h>
@@ -37,7 +37,7 @@ init_strtime()
 static const char *
 get_strtimeptr()
 {
-  if (strlen(strtime) == 0) init_strtime();
+  if (std::strlen(strtime) == 0) init_strtime();
 
   return strtime;
 }
@@ -92,8 +92,7 @@ cdo_append_history(int vlistID, const char *histstring)
     }
   else if (atttype != -1) { return; }
 
-  auto strtimeptr = get_strtimeptr();
-  std::string history = strtimeptr;
+  std::string history = get_strtimeptr();
   history += histstring;
 
   if (!ghistory.empty())
@@ -108,8 +107,8 @@ cdo_append_history(int vlistID, const char *histstring)
 void
 cdo_def_creation_date(int vlistID)
 {
-  if (strlen(datetimestr) == 0) init_strtime();
-  cdiDefAttTxt(vlistID, CDI_GLOBAL, "creation_date", (int) strlen(datetimestr), datetimestr);
+  if (std::strlen(datetimestr) == 0) init_strtime();
+  cdiDefAttTxt(vlistID, CDI_GLOBAL, "creation_date", (int) std::strlen(datetimestr), datetimestr);
 }
 
 static void
diff --git a/src/cdo_output.cc b/src/cdo_output.cc
index cdf3dca73..5c4e70ed0 100644
--- a/src/cdo_output.cc
+++ b/src/cdo_output.cc
@@ -297,7 +297,7 @@ query_user_exit(const std::string &argument)
       if (fgets(usr_rpl, USR_RPL_MAX_LNG, stdin) == nullptr) continue;
 
       // Ensure last character in input string is \n and replace that with \0
-      usr_rpl_lng = strlen(usr_rpl);
+      usr_rpl_lng = std::strlen(usr_rpl);
       if (usr_rpl_lng >= 1)
         if (usr_rpl[usr_rpl_lng - 1] == '\n')
           {
diff --git a/src/cdo_settings.cc b/src/cdo_settings.cc
index 4989ab7b7..49775bd6b 100644
--- a/src/cdo_settings.cc
+++ b/src/cdo_settings.cc
@@ -149,7 +149,7 @@ set_digits(const std::string &arg)
   const char *carg = arg.c_str();
 
   char *ptr1 = 0;
-  if (carg != 0 && (int) strlen(carg) > 0 && carg[0] != ',') Options::CDO_flt_digits = (int) strtol(carg, &ptr1, 10);
+  if (carg != 0 && (int) std::strlen(carg) > 0 && carg[0] != ',') Options::CDO_flt_digits = (int) strtol(carg, &ptr1, 10);
 
   if (Options::CDO_flt_digits < 1 || Options::CDO_flt_digits > 20)
     cdo_abort("Unreasonable value for float significant digits: %d", Options::CDO_flt_digits);
diff --git a/src/cdo_zaxis.cc b/src/cdo_zaxis.cc
index 2da37f229..9f43f085d 100644
--- a/src/cdo_zaxis.cc
+++ b/src/cdo_zaxis.cc
@@ -309,7 +309,7 @@ cdo_define_zaxis(const char *pzaxisfile)
   int zaxisID = CDI_UNDEFID;
   bool isreg = false;
 
-  auto len = strlen(pzaxisfile);
+  auto len = std::strlen(pzaxisfile);
   char *zaxisfile = strdup(pzaxisfile);
 
   int zaxisNumber = 1;
@@ -367,7 +367,7 @@ cdo_define_zaxis(const char *pzaxisfile)
       if (zaxisID == CDI_UNDEFID) cdo_abort("Invalid zaxis description file %s!", zaxisfile);
     }
 
-  free(zaxisfile);
+  std::free(zaxisfile);
 
   return zaxisID;
 }
diff --git a/src/cfortran.h b/src/cfortran.h
index 1e8a8e08b..ee3febac7 100644
--- a/src/cfortran.h
+++ b/src/cfortran.h
@@ -2499,7 +2499,7 @@ debugging only.*/
 #define STRINGV_cfR(A, B, D) _cf_free(B);
 /* A and D as defined above for TSTRING(V) */
 #define RRRRPSTR(A, B, D) \
-  if (B) memcpy(A, B, _cfMIN(strlen(B), D)), (D > strlen(B) ? memset(A + strlen(B), ' ', D - strlen(B)) : 0), _cf_free(B);
+  if (B) memcpy(A, B, _cfMIN(std::strlen(B), D)), (D > strlen(B) ? memset(A + strlen(B), ' ', D - strlen(B)) : 0), _cf_free(B);
 #define RRRRPSTRV(A, B, D) c2fstrv(B, A, D + 1, (D + 1) * _(B, N)), _cf_free(B);
 #ifdef vmsFortran
 #define PSTRING_cfR(A, B, D) RRRRPSTR(A->dsc$a_pointer, B, A->dsc$w_length)
diff --git a/src/cmortable_parser.cc b/src/cmortable_parser.cc
index e38a8f08c..b5d60e459 100644
--- a/src/cmortable_parser.cc
+++ b/src/cmortable_parser.cc
@@ -62,7 +62,7 @@ static char *
 getElementName(char *pline, char *name)
 {
   while (std::isspace((int) *pline)) pline++;
-  auto len = strlen(pline);
+  auto len = std::strlen(pline);
   size_t pos = 0;
   while (pos < len && !std::isspace((int) *(pline + pos)) && *(pline + pos) != '=' && *(pline + pos) != ':') pos++;
 
@@ -77,7 +77,7 @@ static char *
 getElementValue(char *pline)
 {
   while (std::isspace((int) *pline)) pline++;
-  auto len = strlen(pline);
+  auto len = std::strlen(pline);
   if (*pline != '"' && *pline != '\'')
     for (size_t i = 1; i < len; ++i)
       if (pline[i] == '!')
@@ -110,15 +110,15 @@ parse_cmortable_buffer(PMList &pmlist, size_t buffersize, char *buffer)
       auto pline = line;
       while (std::isspace((int) *pline)) pline++;
       if (*pline == '#' || *pline == '!' || *pline == '\0') continue;
-      //  len = (int) strlen(pline);
+      //  len = (int) std::strlen(pline);
 
       int ientry = -1;
       for (ientry = 0; ientry < nentry; ++ientry)
-        if (std::strncmp(pline, listentry[ientry], strlen(listentry[ientry])) == 0) break;
+        if (std::strncmp(pline, listentry[ientry], std::strlen(listentry[ientry])) == 0) break;
 
       if (ientry < nentry)
         {
-          pline += strlen(listentry[ientry]);
+          pline += std::strlen(listentry[ientry]);
 
           if (kvlist.size())
             {
diff --git a/src/commandline.cc b/src/commandline.cc
index 5dd63d155..fd48ae85c 100644
--- a/src/commandline.cc
+++ b/src/commandline.cc
@@ -17,7 +17,7 @@ static void
 initCommandLine(void)
 {
   size_t maxlen = 1;
-  for (int iarg = 0; iarg < gargc; iarg++) maxlen += strlen(gargv[iarg]) + 1;
+  for (int iarg = 0; iarg < gargc; iarg++) maxlen += std::strlen(gargv[iarg]) + 1;
 
   CDO_CommandLine.resize(maxlen);
 
diff --git a/src/datetime.cc b/src/datetime.cc
index e260cc719..0230c3749 100644
--- a/src/datetime.cc
+++ b/src/datetime.cc
@@ -475,7 +475,7 @@ get_timeunits(const std::string &unitsStr, int &incrPeriod, int &incrUnits, int
 CdiDate
 decode_datestring(const std::string &dateString)
 {
-  if (strchr(dateString.c_str() + 1, '-'))
+  if (std::strchr(dateString.c_str() + 1, '-'))
     {
       int year = 1, month = 1, day = 1;
       std::sscanf(dateString.c_str(), "%d-%d-%d", &year, &month, &day);
@@ -487,7 +487,7 @@ decode_datestring(const std::string &dateString)
 CdiTime
 decode_timestring(const std::string &timeString)
 {
-  if (strchr(timeString.c_str(), ':'))
+  if (std::strchr(timeString.c_str(), ':'))
     {
       int hour = 0, minute = 0;
       double fseconds = 0.0;
diff --git a/src/dcw_reader.cc b/src/dcw_reader.cc
index a528c7225..ab21d4b45 100644
--- a/src/dcw_reader.cc
+++ b/src/dcw_reader.cc
@@ -73,7 +73,7 @@ dcw_load_lists(DCW_Lists &dcw_lists)
   size_t n_alloc = 300;
   unsigned int k, n;
   char line[BUFSIZ] = { 0 };
-  DCW_Country_State *Country_State = NULL;
+  // DCW_Country_State *Country_State = NULL;
 
   char path[PATH_MAX] = { 0 };
   if (!dcw_get_path("dcw-countries", ".txt", path)) return -1;
@@ -141,17 +141,19 @@ dcw_load_lists(DCW_Lists &dcw_lists)
 
   // Get list of countries with states
 
-  dim[2] = n;    // Number of countries with states
-  if (0 /*CS*/)  // Wants list returned
-    {
-      Country_State = (DCW_Country_State *) malloc(n * sizeof(struct DCW_Country_State));
-      std::memcpy(Country_State[0].country, states[0].country, 4);
-      for (k = n = 1; k < dim[1]; ++k)
-        {
-          if (std::strcmp(states[k].country, states[k - 1].country)) std::memcpy(Country_State[n++].country, states[k].country, 4);
-        }
-      // *CS = Country_State;
-    }
+  dim[2] = n;  // Number of countries with states
+  /*
+  if (0)  // Wants list returned
+  {
+    Country_State = (DCW_Country_State *) malloc(n * sizeof(struct DCW_Country_State));
+    std::memcpy(Country_State[0].country, states[0].country, 4);
+    for (k = n = 1; k < dim[1]; ++k)
+      {
+        if (std::strcmp(states[k].country, states[k - 1].country)) std::memcpy(Country_State[n++].country, states[k].country, 4);
+      }
+    // *CS = Country_State;
+  }
+  */
 
   // fprintf(stderr, "# DCW: Found %u countries, %u countries with states, and %u states\n", dim[0], dim[2], dim[1]);
 
diff --git a/src/expr.cc b/src/expr.cc
index 766d825c2..fee474360 100644
--- a/src/expr.cc
+++ b/src/expr.cc
@@ -1613,7 +1613,7 @@ ex_not(int init, nodeType *p1)
 static void
 str_add_node_info(char *string, size_t stringlen, nodeType *p, const char *ext)
 {
-  auto len = strlen(string);
+  auto len = std::strlen(string);
   if (p->type == NodeEnum::typeCon) { snprintf(string + len, stringlen - len, "%g%s", p->con().value, ext); }
   else { snprintf(string + len, stringlen - len, "%s[N%zu][L%zu]%s", p->var().name.c_str(), p->param.ngp, p->param.nlev, ext); }
 }
diff --git a/src/expr_fun.cc b/src/expr_fun.cc
index 071047e98..0cd20390c 100644
--- a/src/expr_fun.cc
+++ b/src/expr_fun.cc
@@ -363,7 +363,7 @@ double *
 fld_weights(int gridID, size_t ngp)
 {
   static auto printWarning = true;
-  double *weights = (double *) malloc(ngp * sizeof(double));
+  double *weights = (double *) std::malloc(ngp * sizeof(double));
   for (size_t i = 0; i < ngp; ++i) weights[i] = 1;
 
   if (ngp > 1)
diff --git a/src/fileStream.cc b/src/fileStream.cc
index 4b7dd4d06..43e5f3812 100644
--- a/src/fileStream.cc
+++ b/src/fileStream.cc
@@ -238,7 +238,7 @@ FileStream::def_vlist(int p_vlistID)
       cdo_def_creation_date(p_vlistID);
     }
 
-  if (Options::VersionInfo) cdiDefAttTxt(p_vlistID, CDI_GLOBAL, "CDO", (int) strlen(cdo_comment()), cdo_comment());
+  if (Options::VersionInfo) cdiDefAttTxt(p_vlistID, CDI_GLOBAL, "CDO", (int) std::strlen(cdo_comment()), cdo_comment());
 
 #ifdef _OPENMP
   if (Threading::ompNumMaxThreads > 1)
diff --git a/src/grid_print.cc b/src/grid_print.cc
index 9fac445ee..a0ff9f1f6 100644
--- a/src/grid_print.cc
+++ b/src/grid_print.cc
@@ -17,7 +17,7 @@ constexpr int MaxLen = 120;
 static void
 printDblsPrefixAutoBrk(FILE *fp, int dig, const char *prefix, size_t n, const double vals[])
 {
-  int nbyte0 = strlen(prefix);
+  int nbyte0 = std::strlen(prefix);
   fputs(prefix, fp);
   auto nbyte = nbyte0;
   for (size_t i = 0; i < n; ++i)
@@ -35,7 +35,7 @@ printDblsPrefixAutoBrk(FILE *fp, int dig, const char *prefix, size_t n, const do
 static void
 printIntsPrefixAutoBrk(FILE *fp, const char *prefix, size_t n, const int vals[])
 {
-  int nbyte0 = strlen(prefix);
+  int nbyte0 = std::strlen(prefix);
   fputs(prefix, fp);
   auto nbyte = nbyte0;
   for (size_t i = 0; i < n; ++i)
@@ -53,7 +53,7 @@ printIntsPrefixAutoBrk(FILE *fp, const char *prefix, size_t n, const int vals[])
 static void
 print_bounds(FILE *fp, int dig, const char *prefix, size_t n, size_t nvertex, const double bounds[])
 {
-  int nbyte0 = strlen(prefix);
+  int nbyte0 = std::strlen(prefix);
   fputs(prefix, fp);
   for (size_t i = 0; i < n; ++i)
     {
@@ -66,7 +66,7 @@ print_bounds(FILE *fp, int dig, const char *prefix, size_t n, size_t nvertex, co
 static void
 printMask(FILE *fp, const char *prefix, size_t n, const int mask[])
 {
-  int nbyte0 = strlen(prefix);
+  int nbyte0 = std::strlen(prefix);
   fputs(prefix, fp);
   auto nbyte = nbyte0;
   for (size_t i = 0; i < n; ++i)
@@ -105,7 +105,7 @@ grid_print_attributes(FILE *fp, int gridID)
           std::vector<char> atttxt(attlen + 1);
           cdiInqAttTxt(cdiID, varID, attname, attlen, atttxt.data());
           atttxt[attlen] = 0;
-          if (strchr(atttxt.data(), '"'))
+          if (std::strchr(atttxt.data(), '"'))
             fprintf(fp, "%s = '%s'\n", attname, atttxt.data());
           else
             fprintf(fp, "%s = \"%s\"\n", attname, atttxt.data());
diff --git a/src/grid_read.cc b/src/grid_read.cc
index 6173dc382..a3ed9bcb3 100644
--- a/src/grid_read.cc
+++ b/src/grid_read.cc
@@ -41,7 +41,7 @@ grid_read_data(size_t ikv, size_t nkv, const std::vector<KVMap> &kvmap, GridDesc
       // clang-format off
       if (key == "gridtype")
         {
-           auto gridtype = parameter_to_word(value);
+          auto gridtype = parameter_to_word(value);
 
           if (grid.type != CDI_UNDEFID)
             {
@@ -70,7 +70,7 @@ grid_read_data(size_t ikv, size_t nkv, const std::vector<KVMap> &kvmap, GridDesc
         }
       else if (key == "datatype")
         {
-           auto datatype = parameter_to_word(value);
+          auto datatype = parameter_to_word(value);
           if      (datatype == "double") grid.datatype = CDI_DATATYPE_FLT64;
           else if (datatype == "float")  grid.datatype = CDI_DATATYPE_FLT32;
           else cdo_abort("Invalid datatype: %s (grid description file: %s)", datatype, dname);
@@ -95,7 +95,7 @@ grid_read_data(size_t ikv, size_t nkv, const std::vector<KVMap> &kvmap, GridDesc
       else if (key == "scanningMode")
         {
           grid.scanningMode = 64;
-           auto scmode = parameter_to_int(value);
+          auto scmode = parameter_to_int(value);
           if (scmode == 0 || scmode == 64 || scmode == 96)
             grid.scanningMode = scmode; // -1: not used; allowed modes: <0, 64, 96>; Default is 64
           else
@@ -126,10 +126,10 @@ grid_read_data(size_t ikv, size_t nkv, const std::vector<KVMap> &kvmap, GridDesc
           if (size != nvalues)
             cdo_abort("Number of xcvals=%zu and size of xcvals=%zu differ (grid description file: %s)!", nvalues, size, dname);
 
-          grid.xcvals = (char **) malloc(size * sizeof(char *));
+          grid.xcvals = (char **) std::malloc(size * sizeof(char *));
           size_t xstrlen = 64;
           for (size_t i = 0; i < size; ++i) xstrlen = std::max(xstrlen, values[i].size());
-          for (size_t i = 0; i < size; ++i) grid.xcvals[i] = (char *) malloc((xstrlen + 1) * sizeof(char));
+          for (size_t i = 0; i < size; ++i) grid.xcvals[i] = (char *) std::malloc((xstrlen + 1) * sizeof(char));
           for (size_t i = 0; i < size; ++i) std::strcpy(grid.xcvals[i], parameter_to_word(values[i].c_str()));
         }
       else if (key == "ycvals")
@@ -139,10 +139,10 @@ grid_read_data(size_t ikv, size_t nkv, const std::vector<KVMap> &kvmap, GridDesc
           if (size != nvalues)
             cdo_abort("Number of ycvals=%zu and size of ycvals=%zu differ (grid description file: %s)!", nvalues, size, dname);
 
-          grid.ycvals = (char **) malloc(size * sizeof(char *));
+          grid.ycvals = (char **) std::malloc(size * sizeof(char *));
           size_t ystrlen = 64;
           for (size_t i = 0; i < size; ++i) ystrlen = std::max(ystrlen, values[i].size());
-          for (size_t i = 0; i < size; ++i) grid.ycvals[i] = (char *) malloc((ystrlen + 1) * sizeof(char));
+          for (size_t i = 0; i < size; ++i) grid.ycvals[i] = (char *) std::malloc((ystrlen + 1) * sizeof(char));
           for (size_t i = 0; i < size; ++i) std::strcpy(grid.ycvals[i], parameter_to_word(values[i].c_str()));
         }
       else if (key == "xvals")
diff --git a/src/griddes.cc b/src/griddes.cc
index a131988b0..2050cc5b5 100644
--- a/src/griddes.cc
+++ b/src/griddes.cc
@@ -21,8 +21,6 @@
 #include "grid_read_pingo.h"
 #include "cdi_lockedIO.h"
 
-
-
 static void
 genXboundsRegular(GridDesciption &grid)
 {
@@ -171,15 +169,15 @@ grid_define(GridDesciption &grid)
         if (grid.xcvals)
           {
             // gridDefXCvals(gridID, grid.xcvals);
-            for (size_t i = 0; i < grid.xsize; ++i) free(grid.xcvals[i]);
-            free(grid.xcvals);
+            for (size_t i = 0; i < grid.xsize; ++i) std::free(grid.xcvals[i]);
+            std::free(grid.xcvals);
             cdo_warning("CDI function gridDefXCvals() not implemented!");
           }
         if (grid.ycvals)
           {
             // gridDefYCvals(gridID, grid.ycvals);
-            for (size_t i = 0; i < grid.ysize; ++i) free(grid.ycvals[i]);
-            free(grid.ycvals);
+            for (size_t i = 0; i < grid.ysize; ++i) std::free(grid.ycvals[i]);
+            std::free(grid.ycvals);
             cdo_warning("CDI function gridDefYCvals() not implemented!");
           }
         if (grid.xvals.size()) gridDefXvals(gridID, grid.xvals.data());
@@ -406,7 +404,7 @@ cdo_define_grid(const char *pgridfile)
   bool lalloc = false;
   bool lmpas = false;
 
-  auto len = strlen(pgridfile);
+  auto len = std::strlen(pgridfile);
   if (len > 5 && std::strncmp(pgridfile, "mpas:", 5) == 0)
     {
       lmpas = true;
@@ -514,8 +512,8 @@ cdo_define_grid(const char *pgridfile)
       if (gridID == CDI_UNDEFID) cdo_abort("Invalid grid description file %s!", filename);
     }
 
-  if (lalloc) free(filename);
-  free(gridfile);
+  if (lalloc) std::free(filename);
+  std::free(gridfile);
 
   return gridID;
 }
diff --git a/src/griddes_nc.cc b/src/griddes_nc.cc
index 4ef26d334..852aaaf26 100644
--- a/src/griddes_nc.cc
+++ b/src/griddes_nc.cc
@@ -226,11 +226,11 @@ write_nc_grid(const char *gridfile, int gridID, int *grid_imask)
 
   nce(nc_create(gridfile, NC_CLOBBER, &nc_file_id));
 
-  len = strlen(gridfile);
+  len = std::strlen(gridfile);
   if (gridfile[len - 2] == 'n' && gridfile[len - 1] == 'c') len -= 3;
   nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "title", len, gridfile));
 
-  if (Options::VersionInfo) nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "CDO", (int) strlen(cdo_comment()) + 1, cdo_comment()));
+  if (Options::VersionInfo) nce(nc_put_att_text(nc_file_id, NC_GLOBAL, "CDO", (int) std::strlen(cdo_comment()) + 1, cdo_comment()));
 
   // define grid size dimension
 
diff --git a/src/magics_template_parser.cc b/src/magics_template_parser.cc
index c90b4cf71..615ccb010 100644
--- a/src/magics_template_parser.cc
+++ b/src/magics_template_parser.cc
@@ -165,7 +165,7 @@ _set_magics_parameter_value(const char *, const char *, const char *)
 #if 0
       fprintf(stderr, "param_name : %s\tparam_value: %s\n", param_name, param_value);
 #endif
-      if (strchr(param_value, ';')) sep_char = ';';
+      if (std::strchr(param_value, ';')) sep_char = ';';
       const auto splitStrings = split_string(param_value, sep_char);
       if (splitStrings.size())
         {
@@ -187,7 +187,7 @@ _set_magics_parameter_value(const char *, const char *, const char *)
   // MAGICS++ INT ARRAY  TYPE    PARAMETERS
   else if (cdo_cmpstr(param_type, "intarray"))
     {
-      if (strchr(param_value, ';')) sep_char = ';';
+      if (std::strchr(param_value, ';')) sep_char = ';';
       const auto splitStrings = split_string(param_value, sep_char);
       if (splitStrings.size())
         {
@@ -203,7 +203,8 @@ _set_magics_parameter_value(const char *, const char *, const char *)
   // MAGICS++ STRINGARRAY  TYPE    PARAMETERS
   else if (cdo_cmpstr(param_type, "stringarray"))
     {
-      if (DBG) fprintf(stderr, "Input strarr is %s  Sep char is %s Search char is %c\n", param_value, sep_char.c_str(), search_char);
+      if (DBG)
+        fprintf(stderr, "Input strarr is %s  Sep char is %s Search char is %c\n", param_value, sep_char.c_str(), search_char);
       if (std::strstr(param_value, ";")) sep_char = ';';
 
       if (DBG) fprintf(stderr, "Input strarr is %s  Sep char is %s\n", param_value, sep_char.c_str());
@@ -213,10 +214,10 @@ _set_magics_parameter_value(const char *, const char *, const char *)
         fprintf(stderr, "Input strarr is %s split str count is %d Sep char is %s\n", param_value, (int) splitStrings.size(),
                 sep_char.c_str());
 
-      const char **split_str = (const char **) malloc(splitStrings.size() * sizeof(char *));
+      const char **split_str = (const char **) std::malloc(splitStrings.size() * sizeof(char *));
       for (size_t k = 0, n = splitStrings.size(); k < n; ++k) split_str[k] = splitStrings[k].c_str();
       mag_set1c(param_name, split_str, (int) splitStrings.size());
-      free(split_str);
+      std::free(split_str);
     }
   else
     {
diff --git a/src/param_conversion.cc b/src/param_conversion.cc
index c871634a7..60a9fcc2e 100644
--- a/src/param_conversion.cc
+++ b/src/param_conversion.cc
@@ -25,7 +25,7 @@
 const char *
 parameter_to_word(const char *cstring)
 {
-  auto len = strlen(cstring);
+  auto len = std::strlen(cstring);
 
   for (size_t i = 0; i < len; ++i)
     {
@@ -83,7 +83,7 @@ parameter_to_imax(const char *const cstring)
   char *endptr = nullptr;
   auto ival = strtoimax(cstring, &endptr, 10);
   if (*endptr) parameter_error("Integer", cstring, endptr);
-  int len = strlen(cstring);
+  int len = std::strlen(cstring);
   if ((cstring[0] != '-' && len > 19) || len > 20)
     cdo_abort("Integer parameter %s too long (min=%ld max=%ld)!", cstring, LONG_MIN, LONG_MAX);
   return ival;
@@ -271,7 +271,7 @@ season_to_months(const std::string &season, int *imonths)
 {
   const char *const smons = "JFMAMJJASONDJFMAMJJASOND";
   const int imons[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
-  assert(strlen(smons) == (sizeof(imons) / sizeof(int)));
+  assert(std::strlen(smons) == (sizeof(imons) / sizeof(int)));
 
   if (season == "ANN")
     {
@@ -284,7 +284,7 @@ season_to_months(const std::string &season, int *imonths)
       char *const season_u = strdup(season.c_str());
       cstr_to_upper(season_u);
       const char *const sstr = std::strstr(smons, season_u);
-      free(season_u);
+      std::free(season_u);
       if (sstr != nullptr)
         {
           size_t ks = (size_t) (sstr - smons);
diff --git a/src/pmlist.cc b/src/pmlist.cc
index f12c9efee..74013b0c5 100644
--- a/src/pmlist.cc
+++ b/src/pmlist.cc
@@ -203,7 +203,7 @@ get_number_of_values(const unsigned long ntok, const NamelistToken *tokens)
 static void
 replace_name(char *name)
 {
-  for (size_t pos = 0; pos < strlen(name); pos++) name[pos] = std::tolower(name[pos]);
+  for (size_t pos = 0; pos < std::strlen(name); pos++) name[pos] = std::tolower(name[pos]);
 
   if (cdo_cmpstr(name, "conventions")) std::strcpy(name, "Conventions");
   if (cdo_cmpstr(name, "cn")) std::strcpy(name, "cmor_name");
diff --git a/src/remap_scrip_io.cc b/src/remap_scrip_io.cc
index 96f168abb..1ab4c89bc 100644
--- a/src/remap_scrip_io.cc
+++ b/src/remap_scrip_io.cc
@@ -193,7 +193,7 @@ set_map_method(const RemapSwitches &remapSwitches, bool &needGridarea)
 static void
 put_att_text(int ncId, int ncVarId, const char *name, const char *text)
 {
-  nce(nc_put_att_text(ncId, ncVarId, name, strlen(text), text));
+  nce(nc_put_att_text(ncId, ncVarId, name, std::strlen(text), text));
 }
 
 static int
diff --git a/src/util_fileextensions.cc b/src/util_fileextensions.cc
index 896c5619c..4a491d9b2 100644
--- a/src/util_fileextensions.cc
+++ b/src/util_fileextensions.cc
@@ -36,9 +36,9 @@ static void
 rm_filetypeext(char *file, const char *ext)
 {
   // length of filename
-  auto namelen = strlen(file);
+  auto namelen = std::strlen(file);
   // length of the original file extension
-  auto extlen = strlen(ext);
+  auto extlen = std::strlen(ext);
 
   // delete original extension if it is the expected one
   if (std::strcmp(&file[namelen - extlen], ext) == 0) file[namelen - extlen] = 0;
diff --git a/src/util_string.cc b/src/util_string.cc
index 7a71ff1c1..463c4f8a8 100644
--- a/src/util_string.cc
+++ b/src/util_string.cc
@@ -239,7 +239,7 @@ tokenize_comma_seperated_int_list(const std::string &args)
 void
 cstr_replace_char(char *str_in, char orig_char, char rep_char)
 {
-  if (strchr(str_in, orig_char) == nullptr) return;
+  if (std::strchr(str_in, orig_char) == nullptr) return;
 
   while (*str_in != '\0')
     {
diff --git a/src/util_wildcards.cc b/src/util_wildcards.cc
index 9bcc178b8..5b26adea2 100644
--- a/src/util_wildcards.cc
+++ b/src/util_wildcards.cc
@@ -72,7 +72,7 @@ expand_filename(const char *string)
 {
   char *filename = nullptr;
 
-  if (find_wildcard(string, strlen(string)))
+  if (find_wildcard(string, std::strlen(string)))
     {
 #ifdef HAVE_GLOB_H
       auto glob_flags = get_glob_flags();
diff --git a/src/zaxis_print.cc b/src/zaxis_print.cc
index 3e0290a72..60a3a6fbf 100644
--- a/src/zaxis_print.cc
+++ b/src/zaxis_print.cc
@@ -17,7 +17,7 @@ constexpr int MaxLen = 120;
 static void
 printDblsPrefixAutoBrk(FILE *fp, int dig, const char *prefix, size_t n, const double vals[], size_t extbreak)
 {
-  int nbyte0 = strlen(prefix);
+  int nbyte0 = std::strlen(prefix);
   fputs(prefix, fp);
   int nbyte = nbyte0;
   for (size_t i = 0; i < n; ++i)
@@ -77,9 +77,9 @@ zaxisPrintKernel(int zaxisID, FILE *fp)
       for (int i = 0; i < nlevels; ++i)
         {
           fprintf(fp, "     [%2d] = %.*s\n", i, clen, cvals[i]);
-          free(cvals[i]);
+          std::free(cvals[i]);
         }
-      if (cvals) free(cvals);
+      if (cvals) std::free(cvals);
     }
 
   if (zaxisInqLbounds(zaxisID, nullptr) && zaxisInqUbounds(zaxisID, nullptr))
-- 
GitLab


From 976bb93a66dd359d349d0b5190aa57f52eb2a1b6 Mon Sep 17 00:00:00 2001
From: Uwe Schulzweida <uwe.schulzweida@mpimet.mpg.de>
Date: Mon, 24 Feb 2025 14:30:11 +0100
Subject: [PATCH 5/6] ilaenv.c: changed size if array subnam to 5

---
 src/lib/yac/clapack/SRC/ilaenv.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/lib/yac/clapack/SRC/ilaenv.c b/src/lib/yac/clapack/SRC/ilaenv.c
index 2eb991381..7a477ab1d 100644
--- a/src/lib/yac/clapack/SRC/ilaenv.c
+++ b/src/lib/yac/clapack/SRC/ilaenv.c
@@ -38,13 +38,13 @@ integer ilaenv_(integer *ispec, char *name__, char *opts, integer *n1,
     /* Local variables */
     integer i__;
     // 2025/02/17 US: fix stack overflow
-    char c1[4], c2[4], c3[4], c4[4];
+    char c1[5], c2[5], c3[5], c4[5];
     integer ic, nb, iz, nx;
     logical cname;
     integer nbmin;
     logical sname;
     extern integer ieeeck_(integer *, real *, real *);
-    char subnam[4];
+    char subnam[5];
     extern integer iparmq_(integer *, char *, char *, integer *, integer *, 
 	    integer *, integer *);
 
-- 
GitLab


From b0e12b4647e44a13153c862bd57adf2b559515f2 Mon Sep 17 00:00:00 2001
From: Uwe Schulzweida <uwe.schulzweida@mpimet.mpg.de>
Date: Tue, 25 Feb 2025 14:19:10 +0100
Subject: [PATCH 6/6] intgrid_knn: refactored

---
 src/Intgrid.cc        |  3 ++
 src/interpol.h        |  6 ++--
 src/remap_bicubic.cc  |  6 ++--
 src/remap_bilinear.cc |  6 ++--
 src/remap_conserv.cc  | 10 +++---
 src/remap_knn.cc      | 83 ++++++++++---------------------------------
 6 files changed, 31 insertions(+), 83 deletions(-)

diff --git a/src/Intgrid.cc b/src/Intgrid.cc
index aa8a770bb..d01208b4b 100644
--- a/src/Intgrid.cc
+++ b/src/Intgrid.cc
@@ -271,6 +271,8 @@ public:
   void
   init() override
   {
+    if (this_is_the_only_process()) { cdiDefGlobal("READ_CELL_CORNERS", false); }
+
     INTGRID_BIL = module.get_id("intgridbil");
     INTGRID_DIS = module.get_id("intgriddis");
     INTGRID_NN = module.get_id("intgridnn");
@@ -281,6 +283,7 @@ public:
     operatorID = cdo_operator_id();
 
     useFeldMem = (operatorID == INTGRID_BIL || operatorID == THINOUT || operatorID == BOXAVG);
+    useFeldMem = true;
 
     if (operatorID == INTGRID_BIL || operatorID == INTGRID_DIS || operatorID == INTGRID_NN)
       {
diff --git a/src/interpol.h b/src/interpol.h
index b57cd0358..4e0534e8f 100644
--- a/src/interpol.h
+++ b/src/interpol.h
@@ -15,15 +15,13 @@ class Field;
 void interpolate(const Field &field1, Field &field2);
 void intgrid_bil(const Field &field1, Field &field2);
 void intgrid_1nn(const Field &field1, Field &field2);
-void intgrid_knn(KnnParams knnParams, const Field &field1, Field &field2);
+void intgrid_knn(const KnnParams &knnParams, const Field &field1, Field &field2);
 
 constexpr double
 intlin(double x, double y1, double x1, double y2, double x2)
 {
-  // intlin - lineare interpolation
-
+  // intlin - linear interpolation
   // Uwe Schulzweida  04/05/1995
-
   return (y2 * (x - x1) + y1 * (x2 - x)) / (x2 - x1);
 }
 
diff --git a/src/remap_bicubic.cc b/src/remap_bicubic.cc
index 2869e6315..0dca581f0 100644
--- a/src/remap_bicubic.cc
+++ b/src/remap_bicubic.cc
@@ -325,8 +325,6 @@ remap_bicubic(const Varray<T1> &srcArray, Varray<T2> &tgtArray, double srcMissva
 void
 remap_bicubic(RemapSearch &remapSearch, const Field &field1, Field &field2)
 {
-  auto func = [&](const auto &v1, auto &v2, double missval, size_t numMissVals) {
-    remap_bicubic(v1, v2, missval, numMissVals, remapSearch);
-  };
-  field_operation2(func, field1, field2, field1.missval, field1.numMissVals);
+  auto func = [&](const auto &v1, auto &v2) { remap_bicubic(v1, v2, field1.missval, field1.numMissVals, remapSearch); };
+  field_operation2(func, field1, field2);
 }
diff --git a/src/remap_bilinear.cc b/src/remap_bilinear.cc
index a55820f0d..ad68d1d44 100644
--- a/src/remap_bilinear.cc
+++ b/src/remap_bilinear.cc
@@ -444,8 +444,6 @@ remap_bilinear(const Varray<T1> &srcArray, Varray<T2> &tgtArray, double srcMissv
 void
 remap_bilinear(RemapSearch &remapSearch, const Field &field1, Field &field2)
 {
-  auto func = [&](const auto &v1, auto &v2, double missval, size_t numMissVals) {
-    remap_bilinear(v1, v2, missval, numMissVals, remapSearch);
-  };
-  field_operation2(func, field1, field2, field1.missval, field1.numMissVals);
+  auto func = [&](const auto &v1, auto &v2) { remap_bilinear(v1, v2, field1.missval, field1.numMissVals, remapSearch); };
+  field_operation2(func, field1, field2);
 }
diff --git a/src/remap_conserv.cc b/src/remap_conserv.cc
index 61ec40074..7f045eeec 100644
--- a/src/remap_conserv.cc
+++ b/src/remap_conserv.cc
@@ -775,10 +775,8 @@ remap_conserv(const Varray<T1> &srcArray, Varray<T2> &tgtArray, double srcMissva
 void
 remap_conserv(NormOpt normOpt, RemapSearch &remapSearch, const Field &field1, Field &field2)
 {
-  auto func = [&](const auto &v1, auto &v2, double missval, size_t numMissVals) {
-    remap_conserv(v1, v2, missval, numMissVals, normOpt, remapSearch);
-  };
-  field_operation2(func, field1, field2, field1.missval, field1.numMissVals);
+  auto func = [&](const auto &v1, auto &v2) { remap_conserv(v1, v2, field1.missval, field1.numMissVals, normOpt, remapSearch); };
+  field_operation2(func, field1, field2);
 }
 
 template <typename T>
@@ -996,6 +994,6 @@ remap_zonal_mean(const Varray<T1> &srcArray, Varray<T2> &tgtArray, double srcMis
 void
 remap_zonal_mean(const Varray2D<size_t> &remapIndices, const Varray2D<double> &remapWeights, const Field &field1, Field &field2)
 {
-  auto func = [&](const auto &v1, auto &v2, double missval) { remap_zonal_mean(v1, v2, missval, remapIndices, remapWeights); };
-  field_operation2(func, field1, field2, field1.missval);
+  auto func = [&](const auto &v1, auto &v2) { remap_zonal_mean(v1, v2, field1.missval, remapIndices, remapWeights); };
+  field_operation2(func, field1, field2);
 }
diff --git a/src/remap_knn.cc b/src/remap_knn.cc
index dfdd84b39..80f3b1ea5 100644
--- a/src/remap_knn.cc
+++ b/src/remap_knn.cc
@@ -136,7 +136,7 @@ remap_knn(const Varray<T1> &srcArray, Varray<T2> &tgtArray, double srcMissval, s
       auto &tgtValue = tgtArray[tgtCellIndex];
       tgtValue = missval;
 
-      if (!tgtGrid->mask[tgtCellIndex]) continue;
+      if (tgtGrid->mask.size() && !tgtGrid->mask[tgtCellIndex]) continue;
 
       auto &knnData = knnDataList[ompthID];
       auto pointLL = remapgrid_get_lonlat(tgtGrid, tgtCellIndex);
@@ -155,88 +155,41 @@ remap_knn(const Varray<T1> &srcArray, Varray<T2> &tgtArray, double srcMissval, s
 void
 remap_knn(const KnnParams &knnParams, RemapSearch &remapSearch, const Field &field1, Field &field2)
 {
-  auto func = [&](const auto &v1, auto &v2, double missval, size_t numMissVals) {
-    remap_knn(v1, v2, missval, numMissVals, knnParams, remapSearch);
-  };
-  field_operation2(func, field1, field2, field1.missval, field1.numMissVals);
+  auto func = [&](const auto &v1, auto &v2) { remap_knn(v1, v2, field1.missval, field1.numMissVals, knnParams, remapSearch); };
+  field_operation2(func, field1, field2);
 }
 
+template <typename T1, typename T2>
 void
-intgrid_knn(KnnParams knnParams, const Field &field1, Field &field2)
+intgrid_knn(const Varray<T1> &srcArray, Varray<T2> &tgtArray, int gridID1, int gridID2, double srcMissval, size_t numMissVals,
+            const KnnParams &knnParams)
 {
   auto mapType = RemapMethod::KNN;
-  auto gridID1 = field1.grid;
-  auto gridID2 = field2.grid;
-  auto srcMissval = field1.missval;
-  auto tgtMissval = field2.missval;
-  const auto &srcArray = field1.vec_d;
-  auto &tgtArray = field2.vec_d;
 
   if (Options::cdoVerbose) cdo_print("Called %s()", __func__);
 
-  cdo::Progress progress;
-
-  // Interpolate from source to target grid
-
   RemapType remap;
-
   remap_set_int(REMAP_GENWEIGHTS, 0);
   remap_init_grids(mapType, knnParams.extrapolate, gridID1, remap.srcGrid, gridID2, remap.tgtGrid);
-
-  auto srcGridSize = remap.srcGrid.size;
-  auto tgtGridSize = remap.tgtGrid.size;
-
-  Vmask srcGridMask;
-  if (field1.numMissVals) remap_set_mask(srcArray, srcGridSize, field1.numMissVals, srcMissval, srcGridMask);
-
-  std::vector<KnnData> knnDataList;
-  knnDataList.reserve(Threading::ompNumMaxThreads);
-  for (int i = 0; i < Threading::ompNumMaxThreads; ++i) knnDataList.emplace_back(knnParams);
-
   remap_search_init(mapType, remap.search, remap.srcGrid, remap.tgtGrid);
 
-  cdo::timer timer;
-
-  std::atomic<size_t> numMissVals{ 0 };
-  std::atomic<size_t> atomicCount{ 0 };
-
-  // Loop over target grid
-#ifdef _OPENMP
-#pragma omp parallel for default(shared)
-#endif
-  for (size_t tgtCellIndex = 0; tgtCellIndex < tgtGridSize; ++tgtCellIndex)
-    {
-      atomicCount++;
-      auto ompthID = cdo_omp_get_thread_num();
-      if (ompthID == 0 && tgtGridSize > progressMinSize) progress.update((double) atomicCount / tgtGridSize);
-
-      auto &tgtValue = tgtArray[tgtCellIndex];
-      tgtValue = tgtMissval;
-
-      // if (!tgt_mask[tgtCellIndex]) continue;
-
-      auto &knnData = knnDataList[ompthID];
-      auto pointLL = remapgrid_get_lonlat(&remap.tgtGrid, tgtCellIndex);
-
-      // Find nearest grid points on source grid and distances to each point
-      remap_search_points(remap.search, pointLL, knnData);
-
-      // Compute weights if mask is false, eliminate those points
-      auto numWeights = (srcGridMask.size() > 0) ? knnData.compute_weights(srcGridMask) : knnData.compute_weights();
-      if (numWeights)
-        tgtValue = knnData.array_weights_sum(srcArray);
-      else
-        numMissVals++;
-    }
-
-  field2.numMissVals = numMissVals;
+  remap_knn(srcArray, tgtArray, srcMissval, numMissVals, knnParams, remap.search);
 
   remap_grid_free(remap.srcGrid);
   remap_grid_free(remap.tgtGrid);
-
-  if (Options::cdoVerbose) cdo_print("Point search nearest: %.2f seconds", timer.elapsed());
 }  // intgrid_knn
 
+void
+intgrid_knn(const KnnParams &knnParams, const Field &field1, Field &field2)
+{
+  auto func = [&](const auto &v1, auto &v2) {
+    intgrid_knn(v1, v2, field1.grid, field2.grid, field1.missval, field1.numMissVals, knnParams);
+  };
+  field_operation2(func, field1, field2);
+
+  field2.numMissVals = field_num_mv(field2);
+}
+
 void
 intgrid_1nn(const Field &field1, Field &field2)
 {
-- 
GitLab