NSF Unidata

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[netCDF #DMJ-216367]: Reading a dynamic 2d array.

This archive contains answers to questions sent to Unidata support through mid-2025. Note that the archive is no longer being updated. We provide the archive for reference; many of the answers presented here remain technically correct, even if somewhat outdated. For the most up-to-date information on the use of NSF Unidata software and data services, please consult the Software Documentation first.



Hi Anton,

The problem is that the address of the memory you pass to the
nc_get_vars_text() function with the &flags[0][0] argument is not a contiguous
block of memory of size tlen*flen, as required by the netCDF interface.
Instead, &flags[0][0] is the address of the first row of the flags array,
allocated separately from the other rows inside the loop
 for( int i = 0; i < tlen; i++)
 flags[i] = new char[flen];
so it is really only a block of length flen.  The next row is allocated with a
different new statement, so could be anywhere in memory, and is not likely to
be contiguous with the first row.  You allocate a toatal of tlen*flen chars,
but they are in tlen separate blocks of length flen each, and they are just
located in the heap somewhere, not in a single block.  The called function,
nc_get_vars_text(), has no way of knowing how the memory buffer is organized in
little separated chunks all over the heap, it can only assume there is a single
block of memory it can read values into.

A fix for this is to use the C++ "placement new operator", which constructs an
object using a pre-allocated buffer.  For example, I think this would work:

//create matrix of correct size.
buf = new char[tlen*flen];  // a contiguous block of memory
flags = new char*[tlen];
for( int i = 0; i < tlen; i++)
flags[i] = new (&flags[i*flen]) char[flen]; // use placement new operator
  ...
// the following line should no longer produce a seg fault:
status = nc_get_vars_text( ncfileid, flagid, start, count, NULL, &flags[0][0]
);

--Russ


Russ Rew                                         UCAR Unidata Program
address@hidden                     http://www.unidata.ucar.edu



Ticket Details
===================
Ticket ID: DMJ-216367
Department: Support netCDF
Priority: High
Status: Closed