Unidata / netcdf-c

Official GitHub repository for netCDF-C libraries and utilities.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ncdump crashes if enum variable is defined but not written

mjwoods opened this issue · comments

  • Versions tested: netcdf-c release 4.9.2 and main branch at commit b8d76fe
  • Environment: macOS Ventura with clang version 15.0.0 for target arm64-apple-darwin22.6.0
  • Steps to reproduce: as described below.
  • Impact: The crash in ncdump means that any subsequent contents of the dataset are not displayed.
  • Suggestion: If invalid contents are found in a variable, could a special _INVALID value or a warning message be shown instead of aborting?
  1. Save the following C source code in file test_enum.c:
#include <netcdf.h>

int main(void) {
  int ncid, dimid, varid;
  nc_type typeid;
  short values[2] = {0, 1};
  
  nc_create("test_enum.nc", NC_NETCDF4, &ncid);

  nc_def_dim(ncid, "item", 2, &dimid);

  nc_def_enum(ncid, NC_SHORT, "food", &typeid);
  nc_insert_enum(ncid, typeid, "bread", &values[0]);
  nc_insert_enum(ncid, typeid, "cheese", &values[1]);

  nc_def_var(ncid, "meal", typeid, 1, &dimid, &varid);

#ifdef PUT_VAR
  nc_put_var(ncid, varid, &values);
#endif

  nc_close(ncid);

  return 0;
}
  1. Compile with command as follows (or similar):
clang -o test_enum.exe test_enum.c -lnetcdf 
  1. Run test program:
./test_enum.exe
  1. Run ncdump test_enum.nc, which crashes with the following output:
netcdf test_enum {
types:
  short enum food {bread = 0, cheese = 1} ;
dimensions:
	item = 2 ;
variables:
	food meal(item) ;
data:

NetCDF: Invalid argument
Location: file dumplib.c; fcn ncenum_typ_tostring line 957
 meal = %
  1. Recompile so that the enum variable (meal) is written:
clang -DPUT_VAR -o test_enum.exe test_enum.c -lnetcdf 
  1. Repeat steps 3 and 4 to verify that no error occurs.

To be precise, ncdump returns an error. It does not crash.
This behavior is actually correct. The reason is that the values
in the "meal" variable are set to the default fill value, which is (short)-32767.
This is of course not a legal value for the enum, hence the error.
On the other hand, see PR #2462
and Issue #982.
It might be reasonable to check for the default fill value for the type (-32767 in this case)
and if encountered. return the value "_UNDEFINED".
We probably need to get some input on this: @edhartnett ?

My apologies @DennisHeimbigner - I see now that this is an error message. I am wondering if the invalid enum values could be handled without aborting ncdump, so that other contents of the dataset can be displayed.