# Help Needed: Segmentation Fault in Fortran Program with Dynamic Arrays

**URL:** <https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011>\
**Category:** Homework\
**Created:** [December 29, 2024, 1:30pm UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011 "2024-12-29T13:30:32Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![supra](https://avatars.discourse-cdn.com/v4/letter/s/57b2e6/32.png) [@supra](https://fortran-lang.discourse.group/u/supra)\
**Post date:** [December 29, 2024, 1:30pm UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/1 "2024-12-29T13:30:32Z")

</div>

Hi everyone,  
I’m encountering a segmentation fault in my Fortran program related to dynamic arrays and file reading. My code reads data from two input files, allocates arrays dynamically (e.g., `A`, `K`, `res`), and passes them to a subroutine (`calcul_residus`). Despite initializing and checking array sizes, I still get “Program received signal SIGSEGV: Segmentation fault - invalid memory reference.”

Here’s a brief outline:

1. Allocate arrays based on user input (e.g., `allocate(A(...), K(...), res(...))`).
2. Read file data for variables like `F%z`, and process them in a subroutine.
3. Crash occurs when calling `calcul_residus` or accessing array elements.

I’m a beginner in Fortran, so I apologize if my code is rudimentary or too long. I’ve included my code below for context—sorry if parts are in French (I’m a French speaker), but it shouldn’t stop you from understanding it. Thanks in advance for your help!

program LectureDesDonnees  
use types\_module  
implicit none

```
doubleprecision, external :: calculer_Ki

  !! Interface explicite pour calcul_residus !!
interface
    subroutine calcul_residus(A, nombre_constituants, F_flash, F, K, res)
        use types_module
        implicit none
        doubleprecision, intent(in) :: A(:), K(:)
        doubleprecision, intent(out) :: res(:)
        integer, intent(in) :: nombre_constituants
        type(flash), intent(in) :: F_flash
        type(alimentation), intent(in) :: F
    end subroutine calcul_residus
end interface

!! Déclarations des variables globales !!
type(alimentation) :: F
type(flash) :: F_flash
character(len=100) :: ligne, nom, compose_selectionne
integer :: controle_ouverture, controle_lecture, nombre_constituants
integer :: i, j, err
logical :: compose_trouve, nom_valide
character(len=1) :: premiere_lettre

doubleprecision, allocatable :: A(:)
doubleprecision :: w, T, Hv, hl, HF
doubleprecision,allocatable :: x(:), y(:)
doubleprecision, allocatable :: K(:)
doubleprecision, allocatable :: z(:)
doubleprecision, allocatable :: res(:)

!! Lecture des paramètres du séparateur flash !!
open(20, file="parametres_flash.txt", status='old', action='read', &
     iostat=controle_ouverture)
if (controle_ouverture /= 0) then
    print *, "Erreur : Impossible d'ouvrir parametres_flash.txt"
    stop
end if

read(20, *, iostat=controle_lecture) F_flash%P_flash
if (controle_lecture /= 0) then
    print *, "Erreur : Lecture pression flash échouée."
    stop
end if

read(20, *, iostat=controle_lecture) F_flash%Q_flash
if (controle_lecture /= 0) then
    print *, "Erreur : Lecture puissance flash échouée."
    stop
end if

read(20, *, iostat=controle_lecture) F_flash%T_ref
if (controle_lecture /= 0) then
    print *, "Erreur : Lecture T_ref flash échouée."
    stop
end if

print *, "Parametres du separateur flash :"
print *, "Pression du flash : ", F_flash%P_flash, " atm"
print *, "Puissance echangee du flash :", F_flash%Q_flash, " W"
print *, "Temperature de reference : ", F_flash%T_ref, " K"

close(20)

!! Ouverture du fichier donnees_constituants.txt !!
open(10, file="donnees_constituants.txt", status='old', action='read', &
     iostat=controle_ouverture)
if (controle_ouverture /= 0) then
    print *, "Erreur : Impossible d'ouvrir donnees_constituants.txt"
    stop
end if

!! Lecture paramètres alimentation !!
do
    print *, "Entrez le debit massique de l'alimentation (en kg/h) :"
    read (*, *, iostat=controle_lecture) F%M
    if (controle_lecture /= 0 .or. F%M <= 0.0) then
        print *, "Erreur : Vous devez entrer un débit massique valide. Veuillez reessayer."
    else
        exit
    end if
end do

do
    print *, "Entrez la temperature de l'alimentation (en K) :"
    read (*, *, iostat=controle_lecture) F%T
    if (controle_lecture /= 0) then
        print *, "Erreur : Vous devez entrer une temperature valide."
    else
        exit
    end if
end do

do
    print *, "Entrez la pression de l'alimentation (en atm) :"
    read (*, *, iostat=controle_lecture) F%P
    if (controle_lecture /= 0 .or. F%P <= 0.0) then
        print *, "Erreur : Vous devez entrer une pression valide."
    else
        exit
    end if
end do

do
    print *, "Entrez le nombre de constituants de l'alimentation (en chiffre) :"
    read(*, *, iostat=controle_lecture) nombre_constituants
    if (controle_lecture /= 0) then
        print *, "Erreur : Vous devez entrer un nombre valide. Veuillez reessayer."
    else if (nombre_constituants <= 0) then
        print *, "Erreur : Le nombre doit etre superieur a 0. Veuillez reessayer."
    else
        exit
    end if
end do

!! Allocation !!
allocate(y(nombre_constituants), stat=err)
allocate(x(nombre_constituants), stat=err)
allocate(F%constituants(nombre_constituants), stat=err)
allocate(F%z(nombre_constituants), stat=err)
if (err /= 0) then
    print *, "Erreur lors de l'allocation de memoire"
    stop
end if

!! Lecture constituants !!
F%somme_z = 0.0
do i = 1, nombre_constituants
    nom_valide = .false.
    do while (.not. nom_valide)
        print *, "Entrez le nom du constituant : ", i, "/", nombre_constituants, ":"
        read(*,'(A)') compose_selectionne

        premiere_lettre = compose_selectionne(1:1)
        if (iachar(premiere_lettre)<iachar('A') .or. &
            iachar(premiere_lettre)>iachar('Z')) then
            print *, "Erreur : La première lettre doit etre en majuscule. Veuillez réessayer"
        else
            nom_valide = .true.
            F%constituants(i)%nom = trim(adjustl(compose_selectionne))
        end if
    end do

    do
        print *, "Entrez la fraction massique du constituant", &
            trim(adjustl(compose_selectionne)), &
            " (entre 0 et 1, ex: 0.2) : "
        read(*,*, iostat=controle_lecture) F%z(i)
        if (controle_lecture /= 0 .or. F%z(i)<0.0 .or. F%z(i)>1.0) then
            print *, "Erreur : La fraction massique doit être un nombre entre 0 et 1. Veuillez réessayer."
        else
            F%somme_z = F%somme_z + F%z(i)
            exit
        end if
    end do

    compose_trouve=.false.
    rewind(10)
    do
        read(10,'(A)', iostat=controle_lecture) nom
        if (controle_lecture/=0) exit
        if (trim(adjustl(nom))=="") cycle

        if (trim(adjustl(nom))==trim(adjustl(compose_selectionne))) then
            compose_trouve=.true.
            read(10,*, iostat=controle_lecture) F%constituants(i)%Cpliq
            read(10,*, iostat=controle_lecture) F%constituants(i)%Cpvap
            read(10,*, iostat=controle_lecture) F%constituants(i)%Teb
            read(10,*, iostat=controle_lecture) F%constituants(i)%Hvap
            read(10,*, iostat=controle_lecture) F%constituants(i)%Ai
            read(10,*, iostat=controle_lecture) F%constituants(i)%Bi
            read(10,*, iostat=controle_lecture) F%constituants(i)%Ci
            exit
        else
            do j=1,7
                read(10,*, iostat=controle_lecture)
                if (controle_lecture/=0) exit
            end do
        end if
    end do

    if (.not. compose_trouve) then
        print *, "Erreur : Constituant non trouvé dans le fichier."
    end if
end do
close(10)

if (abs(F%somme_z - 1.0)>1e-6) then
    print *, "Erreur : Somme des fractions massiques !=1 : ", F%somme_z
    stop
end if

!! Calcul K !!
do i=1,nombre_constituants
    K(i) = calculer_Ki(F%constituants(i)%Ai, F%constituants(i)%Bi, &
                       F%constituants(i)%Ci, T, F_flash%P_flash)
end do

```

!! Allocation des tableaux

```
allocate(A(2 * nombre_constituants + 2), stat=err)
if (err /= 0) then
    print *, "Erreur lors de l'allocation de A"
    stop
end if
A = 0.0

allocate(K(nombre_constituants), stat=err)
if (err /= 0) then
    print *, "Erreur lors de l'allocation de K"
    stop
end if
K = 0.0

allocate(res(2 + 2 * nombre_constituants), stat=err)
if (err /= 0) then
    print *, "Erreur lors de l'allocation de res"
    stop
end if
res = 0.0

 !! Initialisation w, x, y, T !!
w = 0.5
do i=1,nombre_constituants
    y(i) = 0.1
    x(i) = 0.2
end do
T=0.0
do i=1,nombre_constituants
    T = T + F%constituants(i)%Teb * F%z(i)
end do

do i = 1, nombre_constituants
    A(i) = 0.2 ! Fraction liquide initiale
    A(nombre_constituants + i) = 0.8 ! Fraction vapeur initiale
end do
A(2 * nombre_constituants + 1) = w
A(2 * nombre_constituants + 2) = T

    if (size(A) /= 2 * nombre_constituants + 2) then
print *, "Erreur : Dimension incorrecte de A dans calcul_residus."
stop

```

end if

if (size(res) /= 2 + 2 \* nombre\_constituants) then  
print \*, “Erreur : Dimension incorrecte de res dans calcul\_residus.”  
stop  
end if

print \*, “Avant calcul\_residus :”  
print \*, “Taille de A :”, size(A), “Valeurs :”, A  
print \*, “Taille de K :”, size(K), “Valeurs :”, K

```
!! Appel de la sous-routine calcul_residus !!
call calcul_residus(A, nombre_constituants, F_flash, F, K, res)

!! Affichage des résidus !!
print *, "Résidus calculés :"
do i = 1, size(res)
    print *, "R(", i, ") = ", res(i)
end do

!! Libération de la mémoire !!
deallocate(A, res, K)

```

end program LectureDesDonnees

!===========================================  
! Fonction calculer\_Ki  
!===========================================  
function calculer\_Ki(Ai, Bi, Ci, T, P\_flash)  
implicit none  
doubleprecision, intent(in) :: Ai, Bi, Ci, T, P\_flash  
doubleprecision :: calculer\_Ki, Psat

```
!! Calcul de Psat avec la loi d'Antoine !!
Psat = exp(Ai - Bi / (T + Ci))
calculer_Ki = Psat / P_flash

```

end function calculer\_Ki

!===========================================  
! Subroutine calcul\_residus  
!===========================================  
subroutine calcul\_residus(A, nombre\_constituants, F\_flash, F, K, res)  
use types\_module  
implicit none  
doubleprecision, intent(in) :: A(:), K(🙂  
doubleprecision, intent(out) :: res(🙂  
integer, intent(in) :: nombre\_constituants  
type(flash), intent(in) :: F\_flash  
type(alimentation), intent(in) :: F  
integer :: i  
doubleprecision :: w, T, Hv, hl, HF

```
    if (size(A) /= 2 * nombre_constituants + 2) then
print *, "Erreur : Dimension incorrecte de A dans calcul_residus."
stop

```

end if

if (size(res) /= 2 + 2 \* nombre\_constituants) then  
print \*, “Erreur : Dimension incorrecte de res dans calcul\_residus.”  
stop  
end if

```
!! Initialisation des inconnues !!
w = A(2 * nombre_constituants + 1)
T = A(2 * nombre_constituants + 2)

```

print \*, “Taille de A :”, size(A)  
print \*, “Taille de res :”, size(res)  
print \*, “Fraction vapeur w :”, w  
print \*, “Température T :”, T

```
!! Calcul des résidus !!
res(1) = 0.0 ! Résidu énergétique
res(2) = 0.0 ! Résidu différentiel
do i = 1, nombre_constituants
    res(2 + i) = w * A(nombre_constituants + i) + (1.0 - w) * A(i) - F%z(i)
    res(2 + nombre_constituants + i) = A(nombre_constituants + i) - K(i) * A(i)
end do

```

end subroutine calcul\_residus

---

<div class="post-metadata">

**Author:** ![Arjen](https://avatars.discourse-cdn.com/v4/letter/a/b9bd4f/32.png) [@Arjen](https://fortran-lang.discourse.group/u/Arjen)\
**Post date:** [December 29, 2024, 2:08pm UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/2 "2024-12-29T14:08:22Z")

</div>

Welcome to the forum!

It will help us help you if you put the program code in via the \</\> icon, as this helps preserve the original format. Now we would have to reconstruct it ;). Also, make sure that the code is compilable and buildable. What you have shown is incomplete - the modules are missing. This makes it impossible to run the program.

But could you indicate where the segmentation violation occurs? Is there any stacktrace?  
What compiler are you using?

If there is no extra information, also if you turn on the relevant stacktrace option of the compiler, it is probably possible to get an idea via strategically inserted print statements.  
Another possibility: turn on array bound checks.

---

<div class="post-metadata">

**Author:** ![supra](https://avatars.discourse-cdn.com/v4/letter/s/57b2e6/32.png) [@supra](https://fortran-lang.discourse.group/u/supra)\
**Post date:** [December 29, 2024, 2:55pm UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/3 "2024-12-29T14:55:34Z")

</div>

Thank you for your response and your guidance! I apologize for not including the full code earlier. Below, I’ve included the relevant parts of my program as well as some additional details.

Full Program Code  
Here’s the code (including the `types_module` and other required parts). I’ve used the

> program LectureDesDonnees  
> use types\_module  
> implicit none  
> doubleprecision, external :: calculer\_Ki  
> !! Interface explicite pour calcul\_residus !!  
> interface  
> subroutine calcul\_residus(A, nombre\_constituants, F\_flash, F, K, res)  
> use types\_module  
> implicit none  
> doubleprecision, intent(in) :: A(:), K(🙂  
> doubleprecision, intent(out) :: res(🙂  
> integer, intent(in) :: nombre\_constituants  
> type(flash), intent(in) :: F\_flash  
> type(alimentation), intent(in) :: F  
> end subroutine calcul\_residus  
> end interface  
> !! Déclarations des variables globales !!  
> type(alimentation) :: F  
> type(flash) :: F\_flash  
> character(len=100) :: ligne, nom, compose\_selectionne  
> integer :: controle\_ouverture, controle\_lecture, nombre\_constituants  
> integer :: i, j, err  
> logical :: compose\_trouve, nom\_valide  
> character(len=1) :: premiere\_lettre  
> doubleprecision, allocatable :: A(🙂  
> doubleprecision :: w, T, Hv, hl, HF  
> doubleprecision,allocatable :: x(:), y(🙂  
> doubleprecision, allocatable :: K(🙂  
> doubleprecision, allocatable :: z(🙂  
> doubleprecision, allocatable :: res(🙂  
> !! Lecture des paramètres du séparateur flash !!  
> open(20, file=“parametres\_flash.txt”, status=‘old’, action=‘read’, &  
> iostat=controle\_ouverture)  
> if (controle\_ouverture /= 0) then  
> print \*, “Erreur : Impossible d’ouvrir parametres\_flash.txt”  
> stop  
> end if  
> read(20, \*, iostat=controle\_lecture) F\_flash%P\_flash  
> if (controle\_lecture /= 0) then  
> print \*, “Erreur : Lecture pression flash échouée.”  
> stop  
> end if  
> read(20, \*, iostat=controle\_lecture) F\_flash%Q\_flash  
> if (controle\_lecture /= 0) then  
> print \*, “Erreur : Lecture puissance flash échouée.”  
> stop  
> end if  
> read(20, \*, iostat=controle\_lecture) F\_flash%T\_ref  
> if (controle\_lecture /= 0) then  
> print \*, “Erreur : Lecture T\_ref flash échouée.”  
> stop  
> end if  
> print \*, “Parametres du separateur flash :”  
> print \*, “Pression du flash : “, F\_flash%P\_flash, " atm”  
> print \*, “Puissance echangee du flash :”, F\_flash%Q\_flash, " W”  
> print \*, "Temperature de reference : “, F\_flash%T\_ref, " K”  
> close(20)  
> !! Ouverture du fichier donnees\_constituants.txt !!  
> open(10, file=“donnees\_constituants.txt”, status=‘old’, action=‘read’, &  
> iostat=controle\_ouverture)  
> if (controle\_ouverture /= 0) then  
> print \*, “Erreur : Impossible d’ouvrir donnees\_constituants.txt”  
> stop  
> end if  
> !! Lecture paramètres alimentation !!  
> do  
> print _, “Entrez le debit massique de l’alimentation (en kg/h) :”  
> read (_, \*, iostat=controle\_lecture) F%M  
> if (controle\_lecture /= 0 .or. F%M \<= 0.0) then  
> print \*, “Erreur : Vous devez entrer un débit massique valide. Veuillez reessayer.”  
> else  
> exit  
> end if  
> end do  
> do  
> print _, “Entrez la temperature de l’alimentation (en K) :”  
> read (_, \*, iostat=controle\_lecture) F%T  
> if (controle\_lecture /= 0) then  
> print _, “Erreur : Vous devez entrer une temperature valide.”  
> else  
> exit  
> end if  
> end do  
> do  
> print , “Entrez la pression de l’alimentation (en atm) :”  
> read (, , iostat=controle\_lecture) F%P  
> if (controle\_lecture /= 0 .or. F%P \<= 0.0) then  
> print , “Erreur : Vous devez entrer une pression valide.”  
> else  
> exit  
> end if  
> end do  
> do  
> print , “Entrez le nombre de constituants de l’alimentation (en chiffre) :”  
> read(, , iostat=controle\_lecture) nombre\_constituants  
> if (controle\_lecture /= 0) then  
> print , “Erreur : Vous devez entrer un nombre valide. Veuillez reessayer.”  
> else if (nombre\_constituants \<= 0) then  
> print , “Erreur : Le nombre doit etre superieur a 0. Veuillez reessayer.”  
> else  
> exit  
> end if  
> end do  
> !! Allocation !!  
> allocate(y(nombre\_constituants), stat=err)  
> allocate(x(nombre\_constituants), stat=err)  
> allocate(F%constituants(nombre\_constituants), stat=err)  
> allocate(F%z(nombre\_constituants), stat=err)  
> if (err /= 0) then  
> print , “Erreur lors de l’allocation de memoire”  
> stop  
> end if  
> !! Lecture constituants !!  
> F%somme\_z = 0.0  
> do i = 1, nombre\_constituants  
> nom\_valide = .false.  
> do while (.not. nom\_valide)  
> print , "Entrez le nom du constituant : ", i, “/”, nombre\_constituants, “:”  
> read(,‘(A)’) compose\_selectionne  
> premiere\_lettre = compose\_selectionne(1:1)  
> if (iachar(premiere\_lettre)\<iachar(‘A’) .or. &  
> iachar(premiere\_lettre)\>iachar(‘Z’)) then  
> print , “Erreur : La première lettre doit etre en majuscule. Veuillez réessayer”  
> else  
> nom\_valide = .true.  
> F%constituants(i)%nom = trim(adjustl(compose\_selectionne))  
> end if  
> end do  
> do  
> print , “Entrez la fraction massique du constituant”, &  
> trim(adjustl(compose\_selectionne)), &  
> " (entre 0 et 1, ex: 0.2) : "  
> read(,, iostat=controle\_lecture) F%z(i)  
> if (controle\_lecture /= 0 .or. F%z(i)\<0.0 .or. F%z(i)\>1.0) then  
> print , “Erreur : La fraction massique doit être un nombre entre 0 et 1. Veuillez réessayer.”  
> else  
> F%somme\_z = F%somme\_z + F%z(i)  
> exit  
> end if  
> end do  
> compose\_trouve=.false.  
> rewind(10)  
> do  
> read(10,‘(A)’, iostat=controle\_lecture) nom  
> if (controle\_lecture/=0) exit  
> if (trim(adjustl(nom))==“”) cycle  
> if (trim(adjustl(nom))==trim(adjustl(compose\_selectionne))) then  
> compose\_trouve=.true.  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Cpliq  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Cpvap  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Teb  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Hvap  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Ai  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Bi  
> read(10,, iostat=controle\_lecture) F%constituants(i)%Ci  
> exit  
> else  
> do j=1,7  
> read(10,_, iostat=controle\_lecture)  
> if (controle\_lecture/=0) exit  
> end do  
> end if  
> end do  
> if (.not. compose\_trouve) then  
> print \*, “Erreur : Constituant non trouvé dans le fichier.”  
> end if  
> end do  
> close(10)  
> if (abs(F%somme\_z - 1.0)\>1e-6) then  
> print \*, "Erreur : Somme des fractions massiques !=1 : ", F%somme\_z  
> stop  
> end if  
> !! Calcul K !!  
> do i=1,nombre\_constituants  
> K(i) = calculer\_Ki(F%constituants(i)%Ai, F%constituants(i)%Bi,  
> F%constituants(i)%Ci, T, F\_flash%P\_flash)  
> end do  
> !! Allocation des tableaux  
> allocate(A(2 \* nombre\_constituants + 2), stat=err)  
> if (err /= 0) then  
> print \*, “Erreur lors de l’allocation de A”  
> stop  
> end if  
> A = 0.0  
> allocate(K(nombre\_constituants), stat=err)  
> if (err /= 0) then  
> print \*, “Erreur lors de l’allocation de K”  
> stop  
> end if  
> K = 0.0  
> allocate(res(2 + 2 \* nombre\_constituants), stat=err)  
> if (err /= 0) then  
> print \*, “Erreur lors de l’allocation de res”  
> stop  
> end if  
> res = 0.0  
> !! Initialisation w, x, y, T !!  
> w = 0.5  
> do i=1,nombre\_constituants  
> y(i) = 0.1  
> x(i) = 0.2  
> end do  
> T=0.0  
> do i=1,nombre\_constituants  
> T = T + F%constituants(i)%Teb \* F%z(i)  
> end do  
> do i = 1, nombre\_constituants  
> A(i) = 0.2 ! Fraction liquide initiale  
> A(nombre\_constituants + i) = 0.8 ! Fraction vapeur initiale  
> end do  
> A(2 \* nombre\_constituants + 1) = w  
> A(2 \* nombre\_constituants + 2) = T  
> if (size(A) /= 2 \* nombre\_constituants + 2) then  
> print \*, “Erreur : Dimension incorrecte de A dans calcul\_residus.”  
> stop  
> end if  
> if (size(res) /= 2 + 2 \* nombre\_constituants) then  
> print \*, “Erreur : Dimension incorrecte de res dans calcul\_residus.”  
> stop  
> end if  
> print \*, “Avant calcul\_residus :”  
> print \*, “Taille de A :”, size(A), “Valeurs :”, A  
> print \*, “Taille de K :”, size(K), “Valeurs :”, K  
> !! Appel de la sous-routine calcul\_residus !!  
> call calcul\_residus(A, nombre\_constituants, F\_flash, F, K, res)  
> ! Affichage des résidus !!  
> print \*, “Résidus calculés :”  
> do i = 1, size(res)  
> print \*, “R(”, i, ") = ", res(i)  
> end do  
> !! Libération de la mémoire !!  
> deallocate(A, res, K)  
> end program LectureDesDonnees  
> !===========================================  
> ! Fonction calculer\_Ki  
> !===========================================  
> function calculer\_Ki(Ai, Bi, Ci, T, P\_flash)  
> implicit none  
> doubleprecision, intent(in) :: Ai, Bi, Ci, T, P\_flash  
> doubleprecision :: calculer\_Ki, Psat  
> !! Calcul de Psat avec la loi d’Antoine !!  
> Psat = exp(Ai - Bi / (T + Ci))  
> calculer\_Ki = Psat / P\_flash  
> end function calculer\_Ki  
> !===========================================  
> ! Subroutine calcul\_residus  
> !===========================================  
> subroutine calcul\_residus(A, nombre\_constituants, F\_flash, F, K, res)  
> use types\_module  
> implicit none  
> doubleprecision, intent(in) :: A(:), K(🙂  
> doubleprecision, intent(out) :: res(🙂  
> integer, intent(in) :: nombre\_constituants  
> type(flash), intent(in) :: F\_flash  
> type(alimentation), intent(in) :: F  
> integer :: i  
> doubleprecision :: w, T, Hv, hl, HF  
> if (size(A) /= 2 \* nombre\_constituants + 2) then  
> print \*, “Erreur : Dimension incorrecte de A dans calcul\_residus.”  
> stop  
> end if  
> if (size(res) /= 2 + 2 \* nombre\_constituants) then  
> print \*, “Erreur : Dimension incorrecte de res dans calcul\_residus.”  
> stop  
> end if  
> !! Initialisation des inconnues !!  
> w = A(2 \* nombre\_constituants + 1)  
> T = A(2 \* nombre\_constituants + 2)  
> print \*, “Taille de A :”, size(A)  
> print \*, “Taille de res :”, size(res)  
> print \*, “Fraction vapeur w :”, w  
> print \*, “Température T :”, T  
> !! Calcul des résidus !!  
> res(1) = 0.0 ! Résidu énergétique  
> res(2) = 0.0 ! Résidu différentiel  
> do i = 1, nombre\_constituants  
> res(2 + i) = w \* A(nombre\_constituants + i) + (1.0 - w) \* A(i) - F%z(i)  
> res(2 + nombre\_constituants + i) = A(nombre\_constituants + i) - K(i) \* A(i)  
> end do  
> end subroutine calcul\_residus

The module file

> module types  
> implicit none  
> type :: constituant  
> doubleprecision :: Cpliq, Cpvap, Teb, Hvap, Ai, Bi, Ci  
> character(len=100) :: nom  
> end type constituant  
> type :: alimentation  
> doubleprecision :: M, T, P, somme\_z  
> type(constituant), allocatable :: constituants(🙂  
> doubleprecision, allocatable :: z(🙂  
> end type alimentation  
> type :: flash  
> doubleprecision :: P\_flash, Q\_flash, T\_ref  
> end type flash  
> end module types\>

I will also provide the two text files from which the different data of the code are extracted.

donnees\_constituants :

> Ethane  
> 3333.73 (Cp liquide en J/kg.K)  
> 1566.5 (Cp vapeur en J/kg.K)  
> 184.55 (Température d’ébulition en K)  
> 349860 (Chaleur latente de vaporisation en J/kg)  
> 16.3623 (A coefficient d’antoine pour P en atm et T en K)  
> 1793.97 (B coefficient d’antoine pour P en atm et T en K)  
> 0.0936281 (C coefficient d’antoine pour P en atm et T en K)

> Propane  
> 2383.15727 (Cp liquide en J/kg.K)  
> 1462.67909 (Cp vapeur en J/kg.K)  
> 231.11 (Température d’ébulition en K)  
> 400152.455 (Chaleur latente de vaporisation en J/kg)  
> 15.7682 (A coefficient d’antoine pour P en atm et T en K)  
> 1887.25 (B coefficient d’antoine pour P en atm et T en K)  
> -24.4814 (C coefficient d’antoine pour P en atm et T en K)

> N-butane  
> 2222.90545 (Cp liquide en J/kg.K)  
> 1495.28455 (Cp vapeur en J/kg.K)  
> 272.65 (Température d’ébulition en K)  
> 403590.727 (Chaleur latente de vaporisation en J/kg)  
> 15.7759 (A coefficient d’antoine pour P en atm et T en K)  
> 2198.40 (B coefficient d’antoine pour P en atm et T en K)  
> -32.1604 (C coefficient d’antoine pour P en atm et T en K)

> Isobutane  
> 2197.29182 (Cp liquide en J/kg.K)  
> 1443.49364 (Cp vapeur en J/kg.K)  
> 261.43 (Température d’ébulition en K)  
> 374696.90 (Chaleur latente de vaporisation en J/kg)  
> 15.4810 (A coefficient d’antoine pour P en atm et T en K)  
> 2000.08 (B coefficient d’antoine pour P en atm et T en K)  
> -35.1819 (C coefficient d’antoine pour P en atm et T en K)

and donnes\_flash :

> 2 (Pression du flash en atm)  
> 0 (Puissance echangé du flash)  
> 298 (Température de référence en K)\>

Apologies if some variable names or comments are in French.

Issue Description  
The segmentation fault happens when I run the program, specifically at this line:  
fortran  
K(i) = calculer\_Ki(F%constituants(i)%Ai, F%constituants(i)%Bi, F%constituants(i)%Ci, T, F\_flash%P\_flash)

I used GDB to debug the issue, and here’s what the stack trace shows:  
Thread 1 received signal SIGSEGV, Segmentation fault.  
0x0000000000404199 in lecturedesdonnees () at main2.f90:202  
202 F%constituants(i)%Ci, T, F\_flash%P\_flash)  
(gdb) backtrace  
#0 0x0000000000404199 in lecturedesdonnees () at main2.f90:202  
#1 0x0000000000405034 in main (argc=1, argv=0x6b18e0) at main2.f90:2  
#2 0x00000000004013c7 in \_\_tmainCRTStartup ()  
#3 0x00000000004014fb in mainCRTStartup ()  
(gdb)"

Steps I’ve Tried

- I verified that all arrays are properly allocated before use by adding `print` statements and inspecting values in GDB.
- I checked array sizes to ensure no out-of-bounds access occurs.
- I re-initialized all arrays and variables (e.g., `A`, `K`, `res`, etc.) before using them.  
-I checked the value of F%constituants(i) since it came from a text file and all of them are correct
- Despite these precautions, the segmentation fault persists.

Questions

1. Based on the stack trace, is there anything obvious that might cause this segmentation fault?
2. Could the problem be related to how the `types_module` is structured, or perhaps something subtle in my logic for `K` or `F%constituants`?
3. Do you recommend any additional debugging steps? For instance, should I try something beyond `GDB` or other compiler options?

Thank you for your patience and assistance! I’m still learning Fortran, so any tips or guidance would be greatly appreciated.

---

<div class="post-metadata">

**Author:** ![supra](https://avatars.discourse-cdn.com/v4/letter/s/57b2e6/32.png) [@supra](https://fortran-lang.discourse.group/u/supra)\
**Post date:** [December 29, 2024, 3:13pm UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/4 "2024-12-29T15:13:07Z")

</div>

Okay I found what was my error, thanks y’all for the help

---

<div class="post-metadata">

**Author:** ![Arjen](https://avatars.discourse-cdn.com/v4/letter/a/b9bd4f/32.png) [@Arjen](https://fortran-lang.discourse.group/u/Arjen)\
**Post date:** [December 30, 2024, 9:40am UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/5 "2024-12-30T09:40:48Z")

</div>

Could you tell us about the error and how you found it? It could help others 🙂 .

Also, I noted that you did not use the \</\> formatting option, as the code appears in different fonts/styles, including smileys.

As for debugging options: gdb is a very useful tool, but if your program contains large loops and it fails somewhere in the middle, it can be tedious to step through the statements one by one. I usually resort to print statements and if I use an interactive debugger, then a construct like:

```fortran
do i = 1,big_number
     ... loads of statements
     ! From the print statements I have detected it is going wrong somewhere around this iteration 
     if ( i == 10100 ) then
          write(*,*) 'Here!'
    endif
    ... the rest
enddo

```

can help skip the irrelevant iterations: put a break at the write statement.

BTW, the code above was formatted using `fortran and ` - effectively what \</\> brings in. Just add “fortran” for Fortran code and nothing for the input you showed.

---

<div class="post-metadata">

**Author:** ![Arjen](https://avatars.discourse-cdn.com/v4/letter/a/b9bd4f/32.png) [@Arjen](https://fortran-lang.discourse.group/u/Arjen)\
**Post date:** [December 30, 2024, 9:44am UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/6 "2024-12-30T09:44:07Z")

</div>

Argh, the formatting is done by three backticks at the start and at the end - the standalone accent grave. Follow them by the keyword fortran to have coloured code. (The converter now hides them in my previous post.)

---

<div class="post-metadata">

**Author:** ![TomBeam](https://avatars.discourse-cdn.com/v4/letter/t/dec6dc/32.png) [@TomBeam](https://fortran-lang.discourse.group/u/TomBeam)\
**Post date:** [January 3, 2025, 3:45pm UTC](https://fortran-lang.discourse.group/t/help-needed-segmentation-fault-in-fortran-program-with-dynamic-arrays/9011/7 "2025-01-03T15:45:50Z")

</div>

Supra, what was your error?
