ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

ASM x86: String Length Calculation with Null Termination Check

ASM x86

Goal -- WPM

Ready
Exercise Algorithm Area
1section .text
2global calculate_string_length
3
4calculate_string_length:
5; Input: rdi = pointer to the null-terminated string
6; Output: rax = length of the string
7
8; Check for null pointer input
9test rdi, rdi
10jz .null_pointer_error
11
12; Initialize length counter
13xor rax, rax
14
15.loop_start:
16; Load the current byte
17mov cl, byte [rdi + rax]
18
19; Check for null terminator
20test cl, cl
21jz .end_loop
22
23; Increment length counter
24inc rax
25
26; Optional: Add a check for excessively long strings to prevent infinite loops
27; cmp rax, MAX_STRING_LENGTH ; Define MAX_STRING_LENGTH elsewhere
28; jl .loop_start
29; jmp .string_too_long_error
30
31jmp .loop_start
32
33.end_loop:
34ret
35
36.null_pointer_error:
37; Handle null pointer: return -1 or a specific error code
38mov rax, -1
39ret
40
41; .string_too_long_error:
42; ; Handle excessively long string
43; mov rax, -2 ; Or another error code
44; ret
Algorithm description viewbox

ASM x86: String Length Calculation with Null Termination Check

Algorithm description:

This ASM x86 function calculates the length of a null-terminated string. It iterates through the string character by character until it encounters the null terminator (ASCII 0). This is a fundamental operation used in many string manipulation tasks, such as memory allocation for strings or comparing string lengths. It's crucial for basic text processing in low-level programming.

Algorithm explanation:

The `calculate_string_length` function takes a pointer to a string in `rdi` and returns its length in `rax`. It first checks if the input pointer is null; if so, it returns -1. Otherwise, it initializes a counter `rax` to zero. The function then enters a loop, loading each byte of the string into `cl`. If `cl` is zero (the null terminator), the loop terminates. Otherwise, the counter `rax` is incremented, and the loop continues. This approach has a time complexity of O(n), where n is the length of the string, as each character is examined once. The space complexity is O(1) as it only uses a few registers. The invariant maintained is that `rax` always holds the number of characters processed so far that are not the null terminator. The loop correctly terminates upon finding the null byte, ensuring accurate length calculation.

Pseudocode:

FUNCTION calculate_string_length(string_pointer):
  IF string_pointer IS NULL THEN
    RETURN -1
  END IF
  length = 0
  LOOP:
    current_char = character at (string_pointer + length)
    IF current_char IS 0 THEN
      EXIT LOOP
    END IF
    length = length + 1
  END LOOP
  RETURN length
END FUNCTION