4. Characters

by gg582 · 2026-05-27 05:13:48 · 22 views

Here is a technical overview of handling characters and strings in Fortran 2018, structured according to internal logic, memory allocation behavior, and interface boundaries.


1. Core Allocation and Memory Layout

In Fortran 2018, strings are declared using the character keyword. The storage size is determined by two parameters: len (length) and kind (character set encoding).

Static Character Arrays

Static declarations allocate a fixed-size contiguous memory block. Unused trailing bytes are automatically padded with blanks (0x20).

character(len=64) :: buffer
buffer = "sys_init" ! Bytes 9 to 64 are padded with spaces

Deferred-Length (Dynamic Allocation)

To eliminate memory overhead and manual tracking of string lengths, use deferred-length characters via the allocatable attribute. The runtime environment handles reallocation automatically upon assignment.

character(len=:), allocatable :: dynamic_payload

dynamic_payload = "kernel_panic_log_data" ! Allocated at length 21
dynamic_payload = "short_err"              ! Automatically reallocated to length 9


2. String Manipulation Logic

Truncation and Padding Prevention

Standard assignments to fixed-length strings trigger truncation or blank padding. To manage data flow accurately, utilize intrinsic functions to control whitespace logic.

character(len=10) :: standard_str
character(len=20) :: explicit_str

standard_str = "data"
! adjustl shifts characters left, removing leading whitespaces
! trim strips all trailing blanks
explicit_str = adjustl(standard_str) // "_valid" 

Substring Slicing

Fortran uses a 1-based indexing system for slicing contiguous memory blocks.

character(len=8) :: target
target = "12345678"
print *, target(3:6) ! Returns "3456"


3. ABI Interoperability with C (ISO_C_BINDING)

Fortran 2018 ensures strict binary compatibility with C types through the intrinsic module iso_c_binding.

Null-Termination Specification

Fortran strings do not implicitly terminate with a null character (\0). To pass a string safely to a C interface without causing a buffer overflow, you must append c_null_char.

use, intrinsic :: iso_c_binding, only : c_char, c_null_char
implicit none

character(kind=c_char, len=:), allocatable :: c_compatible_string

! Explicit null-termination for C ABI enforcement
c_compatible_string = "fetch_framebuffer" // c_null_char


4. Performance Specifications

Operation Mechanism Overhead Considerations
fixed_len = "str" Static copy + Blank padding Minimal CPU cycles, fixed memory footprint.
alloc_len = "str" Heap reallocation check Triggers malloc/free wrappers if bounds mismatch.
trim(string) Runtime descriptor scan Scans backward to identify the last non-blank byte.
Back

Comments

No comments yet.