lammps/lammps

[BUG] Fortran interface, c2f_string shape

mgoonde opened this issue · 1 comments

Summary

Launching lammps as library from fortran, passing commands as strings causes Fortran error.
Reason: incorrect shape in C_F_POINTER when transforming F string to C?

LAMMPS Version and Platform

Version: LAMMPS (7 Feb 2024 - Development - patch_7Feb2024_update1-275-g207a14f351)
Platform: Ubuntu 22.04
GCC version: 11.4.0

Expected Behavior

Actual Behavior

Simple program (see attached files, directory src):

use liblammps
implicit none
type( lammps ) :: lmp

lmp = lammps()
call lmp% command( "units_metal" )
call lmp% close()

Passing the single command call lmp% command( "units metal" ) causes fortran runtime error:

At line 3692 of file /home/mgunde/lmp/fortran/lammps.f90
Fortran runtime error: Index '2' of dimension 1 of array 'c_string' above upper bound of 1

Error termination. Backtrace:
#0  0x7bbb9dc23960 in ???
#1  0x7bbb9dc244d9 in ???
#2  0x7bbb9dc24ad6 in ???
#3  0x58cf48f13d13 in f2c_string
	at /home/mgunde/lmp/fortran/lammps.f90:3692
#4  0x58cf48f2cf26 in __liblammps_MOD_lmp_open
	at /home/mgunde/lmp/fortran/lammps.f90:1008
#5  0x58cf48f2d248 in MAIN__
	at /home/mgunde/fortr/lmpbug/src/main.f90:8
#6  0x58cf48f2d31e in main
	at /home/mgunde/fortr/lmpbug/src/main.f90:3

The error is resolved by modifying the fortran/lammps.f90 FUNCTION f2c_string() line 3690:
CALL C_F_POINTER(ptr, c_string, [1])
replacing by:
CALL C_F_POINTER(ptr, c_string, [n+1])

Interestingly, writing a makefile which compiles the objects into /lammps/fortran directory seems to not be affected by this error. See attached files, folder src1.

Further Information, Files, and Links

lmp_c2fstring_err.tar.gz

Your observation is correct. This is a bug in the LAMMPS fortran module.

BTW: the preferred way to compile the LAMMPS fortran module would be something like this:

FC = gfortran
SRC = $(PWD)
MAIN = main.x

## path to lammps root
LMP_PATH = /home/mgunde/lmp
LMPLIB = $(LMP_PATH)/src/liblammps.so -Wl,-rpath,$(LMP_PATH)/src
MOD = ${LMP_PATH}/fortran/lammps.f90
FFLAGS := -Wall -fbounds-check -g -cpp

# -- Command
default: main

main: lmp
^_______$(FC) -o $(MAIN) $(FFLAGS) $(MOD) main.f90 $(LMPLIB)

## object files
%.o: %.f90
^_______$(FC) -c $^ -o $@

clean:
^_______rm -rf *.o *.mod *.x