Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Strings memory allocation

dzuba
Beginner
634 Views
Hi!

I have to use very long string (~1M).

I can declarate such variable:

character(1000000) myString

But then I use it - I get Memory Errors sometimes.

I have to allocate memory for a big strings, I see,

but I can't use arrays. If I declare such array:

character(LEN=1), dimension(:), allocatable :: myString

I see compilation error if try to use any string function, for example:

A scalar-valued argument is required in this context. [TRIM]

So, how to allocate memory for String in fortran.

Thanks!
0 Kudos
4 Replies
Steven_L_Intel1
Employee
634 Views
Fortran 95 does not have allocatable strings. That is a Fortran 2003 feature. Unfortunately, there isn't a good alternative that still lets you use the standard string intrinsics. The big problem is that there isn't a way for you to specify the length of an allocated string.
0 Kudos
anthonyrichards
New Contributor III
634 Views
Can you not also store characters in INTEGER and REAL variables?
0 Kudos
Steven_L_Intel1
Employee
634 Views
Sure you can. The problem is if you want to use character intrinsics such as TRIM on them.

You can do something like this:


character*100000 bigstring
pointer (p_bigstring, bigstring)
p_bigstring = malloc(size_you_want)


Now, as long as you're careful to always access bigstring with a valid substring, say, bigstring(1:size_you_want), you can call string intrinsics.
0 Kudos
Jugoslav_Dujic
Valued Contributor II
634 Views
There are several VF-compatible implementations of F2003 module ISO_VARYING_STRINGS on the internet. I think Richard Townsend's (I might be wrong) uses allocatable components (TR15581) and is less prone to memory leaks.

Whichever implementation you choose, though, you have to reconsider how you use standard intrinsics on such large strings. E.g. if a 1-million long string contains 30 kB of text, TRIM() will have to start from the 1,000,000th position to search for non-blank character. Assignment to full string will have to blank-pad few hundred thousands of entries, etc. I recommend a do-it-yourself approach, where you take care of valid length yourself, do assignments only to the parts of the string, etc, to retain efficiency. So, maybe the array of character(1) is not so bad idea after all...
0 Kudos
Reply