Skip to content

Commit

Permalink
Eliminated duplicate strlen() call, fix strlen() truncation to int
Browse files Browse the repository at this point in the history
strlen() is O(N) and thus slow for long strings. modify_field() always calls strlen() at the beginning, but was sometimes calling it again later. No need to compute the length twice.

Also use size_t for the return value of strlen() instead of truncating to int.
  • Loading branch information
seanm authored and hjmjohnson committed Dec 20, 2024
1 parent 04ac6b1 commit 8f72d11
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
10 changes: 6 additions & 4 deletions nifti2/nifti_tool.c
Original file line number Diff line number Diff line change
Expand Up @@ -3828,14 +3828,16 @@ int modify_all_fields( void * basep, nt_opts * opts, field_s * fields, int flen)
*----------------------------------------------------------------------*/
int modify_field(void * basep, field_s * field, const char * data)
{
float fval;
float fval;
const char * posn = data;
int val, max, fc, nchars;
int val, max, fc, nchars;
size_t dataLength;

if( g_debug > 1 )
fprintf(stderr,"+d modifying field '%s' with '%s'\n", field->name, data);

if( !data || strlen(data) == 0 )
dataLength = data ? strlen(data) : 0;
if( dataLength == 0 )
{
fprintf(stderr,"** no data for '%s' field modification\n",field->name);
return 1;
Expand Down Expand Up @@ -3991,7 +3993,7 @@ int modify_field(void * basep, field_s * field, const char * data)
case NT_DT_STRING:
{
char * dest = (char *)basep + field->offset;
nchars = strlen(data);
nchars = dataLength;
strncpy(dest, data, field->len);
if( nchars < field->len ) /* clear the rest */
memset(dest+nchars, '\0', field->len-nchars);
Expand Down
6 changes: 4 additions & 2 deletions niftilib/nifti1_tool.c
Original file line number Diff line number Diff line change
Expand Up @@ -2896,11 +2896,13 @@ int modify_field(void * basep, field_s * field, const char * data)
float fval;
const char * posn = data;
int val, max, fc, nchars;
size_t dataLength;

if( g_debug > 1 )
fprintf(stderr,"+d modifying field '%s' with '%s'\n", field->name, data);

if( !data || strlen(data) == 0 )
dataLength = data ? strlen(data) : 0;
if( dataLength == 0 )
{
fprintf(stderr,"** no data for '%s' field modification\n",field->name);
return 1;
Expand Down Expand Up @@ -3015,7 +3017,7 @@ int modify_field(void * basep, field_s * field, const char * data)
case NT_DT_STRING:
{
char * dest = (char *)basep + field->offset;
nchars = strlen(data);
nchars = dataLength;
strncpy(dest, data, field->len);
if( nchars < field->len ) /* clear the rest */
memset(dest+nchars, '\0', field->len-nchars);
Expand Down

0 comments on commit 8f72d11

Please sign in to comment.