characters passing ocurrs error when fortran calling c

my main fortran code, main.f90:

program main
implicit none

write(*,*)  "abcdefghijklmnopqrstuvwxyz"
call cprint(" Hello world!")
call cprint(" Hello hell!")

end program main

“cprint” is a c subroutine here, foo.c

#include <stdio.h>
void cprint_(char* string){
printf("%s", string);
}

The result output is

 abcdefghijklmnopqrstuvwxyz
 Hello world!abcdefghijklmnopqrstuvwxyz Hello hell! Hello world!abcdefghijklmnopqrstuvwxyz

I use the debug tool “pgdbg” to check the variable passing, I found that
the fortran trans “Hello world!abcdefghijklmnopqrstuvwxyz” to string in cprint.

I can’t understand this. How to solve it.
Thank you.

btw: my compile command is

gcc -g -c foo.c
pgf90 -g -c main.f90
pgf90 -g -o bar.out main.o foo.o

My pgf90 version is 5.2-1, gcc version is 3.4.3

Hi Landau,

The C printf function is expecting a null terminated character array. Fortran does not add the null character to the end of a string. When printf tries to print “Hello World!”, it keeps printing values until it happens upon a 0.

To fix, add the null termination character (char(0) or ‘\0’) at the end of your Fortran strings.

program main
implicit none

write(*,*)  "abcdefghijklmnopqrstuvwxyz"
call cprint(" Hello world! " // char(0)) ! or  " Hello world! \0"
call cprint(" Hello hell! " // char(0))  ! or " Hello hell! \0"

end program main



% gcc cprint.c -c
% pgf90 main.f90 -c
% pgf90 main.o cprint.o
% a.out
 abcdefghijklmnopqrstuvwxyz
 Hello world!  Hello hell!

Sincerely,
Mat

Hi Mat,
That real do!
Thank you very much!

cheers,
Landau