Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the length of a constant string?

I have defined a string label as follows in the data section:

.data
    array:
        .string "Hello World!"

My question is, how would I go about retrieving the length of the string (11)? Do I have to use a for loop and iterate through every bit in the memory section occupied by the string label until I find a character (integer section of 4 bytes) set to 0?

like image 766
Adam Lee Avatar asked Nov 29 '25 08:11

Adam Lee


1 Answers

Get the address of the byte following the string, and subtract the address of array.

This can be done by placing another label at the end of the string, or by using . which refers to the current address. Examples:

    .data
str1:
    .string "Hello"
str1_end:
    str1_len = (str1_end - str1)

str2:
    .string "Goodbye"
    str2_len = (. - str2)

    .text
    .global foo
foo:
    movl $str1_len, %eax
    movl $str2_len, %ebx

This assembles into

    movl $6, %eax
    movl $8, %ebx

By the way, if your string is really constant, consider placing it in .section .rodata instead of .data.

like image 143
Nate Eldredge Avatar answered Dec 02 '25 00:12

Nate Eldredge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!