I tried to do this function DFS recursively in assembly and I keep recieving “Segmentation fault” and I don’t know from where.
neighbours_t expand(uint32_t node);
void dfs(uint32_t node, neighbours_t *(*expand)(uint32_t node));
%include "../include/io.mac"
; The `expand` function returns an address to the following type of data
; structure.
struc neighbours_t
.num_neighs resd 1 ; The number of neighbours returned.
.neighs resd 1 ; Address of the vector containing the `num_neighs` neighbours.
; A neighbour is represented by an unsigned int (dword).
endstruc
section .bss
; Vector for keeping track of visited nodes.
visited resd 10000
global visited
section .data
; Format string for printf.
fmt_str db "%u", 10, 0
section .text
global dfs
extern printf
; Define the structure for neighbours
struc neighbours_t
.num_neighs resd 1
.neighs resd 1
endstruc
; Function to perform depth-first search
; Input:
; node -> uint32_t node id
; expand -> pointer to function expand(uint32_t node) returning neighbours_t*
dfs:
push ebp
mov ebp, esp
push edx
push esi
push edi
; Arguments
mov eax, [ebp+8] ; node
mov ebx, [ebp+12] ; expand function pointer
; Mark the node as visited
mov edx, eax
mov ecx, visited
mov byte [ecx + edx * 4], 1
; Mark node as visited
; Print the visited node
push eax
push fmt_str
call printf
add esp, 8
; Get neighbours
push eax ; Save current node
call ebx ; Call expand function
pop eax ; Restore current node
; Iterate over neighbours
mov esi, eax ; neighbours_t* to esi
mov ecx, [esi + neighbours_t.num_neighs] ; Number of neighbours
mov edi, [esi + neighbours_t.neighs] ; Address of neighbours array
xor eax, eax ; Loop counter
dfs_loop:
cmp eax, ecx ; Check if all neighbours visited
jge dfs_end
; Get neighbour
mov edx, [edi + eax*4]
; Check if neighbour is visited
mov ebx, visited
cmp byte [ebx + edx * 4], 0 ; Check if not visited
jne dfs_next_neighbour ; If visited, skip
; Recursively call dfs for unvisited neighbour
push edx
push ebx
call dfs
pop ebx
pop edx
dfs_next_neighbour:
inc eax ; Increment loop counter
jmp dfs_loop
dfs_end:
pop edx
pop esi
pop edi
leave
ret
I tried to do this function DFS recursively in assembly and I keep recieving “Segmentation fault” and I don’t know from where.
New contributor
Alexandra Dinu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.