Skip to content

Commit 0cbfc78

Browse files
committed
Optimize trie operations by replacing tail recursion with iteration
Replace tail-recursive calls in insert_trie() and find_trie() with an iterative loop to reduce function call overhead and avoid potential stack overflow issues. The logic remains functionally equivalent, improving performance and stability.
1 parent 4b8c4e6 commit 0cbfc78

File tree

1 file changed

+37
-25
lines changed

1 file changed

+37
-25
lines changed

src/globals.c

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -87,25 +87,31 @@ char *elf_section;
8787
*/
8888
int insert_trie(trie_t *trie, char *name, int funcs_index)
8989
{
90-
char first_char = *name;
91-
int fc = first_char;
92-
if (!fc) {
93-
if (!trie->index)
94-
trie->index = funcs_index;
95-
return trie->index;
96-
}
97-
if (!trie->next[fc]) {
98-
/* FIXME: The func_tries_idx variable may exceed the maximum number,
99-
* which can lead to a segmentation fault. This issue is affected by the
100-
* number of functions and the length of their names. The proper way to
101-
* handle this is to dynamically allocate a new element.
102-
*/
103-
trie->next[fc] = func_tries_idx++;
104-
for (int i = 0; i < 128; i++)
105-
FUNC_TRIES[trie->next[fc]].next[i] = 0;
106-
FUNC_TRIES[trie->next[fc]].index = 0;
90+
char first_char;
91+
int fc;
92+
93+
while (1) {
94+
first_char = *name;
95+
fc = first_char;
96+
if (!fc) {
97+
if (!trie->index)
98+
trie->index = funcs_index;
99+
return trie->index;
100+
}
101+
if (!trie->next[fc]) {
102+
/* FIXME: The func_tries_idx variable may exceed the maximum number,
103+
* which can lead to a segmentation fault. This issue is affected by
104+
* the number of functions and the length of their names. The proper
105+
* way to handle this is to dynamically allocate a new element.
106+
*/
107+
trie->next[fc] = func_tries_idx++;
108+
for (int i = 0; i < 128; i++)
109+
FUNC_TRIES[trie->next[fc]].next[i] = 0;
110+
FUNC_TRIES[trie->next[fc]].index = 0;
111+
}
112+
trie = &FUNC_TRIES[trie->next[fc]];
113+
name = name + 1;
107114
}
108-
return insert_trie(&FUNC_TRIES[trie->next[fc]], name + 1, funcs_index);
109115
}
110116

111117
/**
@@ -120,13 +126,19 @@ int insert_trie(trie_t *trie, char *name, int funcs_index)
120126
*/
121127
int find_trie(trie_t *trie, char *name)
122128
{
123-
char first_char = *name;
124-
int fc = first_char;
125-
if (!fc)
126-
return trie->index;
127-
if (!trie->next[fc])
128-
return 0;
129-
return find_trie(&FUNC_TRIES[trie->next[fc]], name + 1);
129+
char first_char;
130+
int fc;
131+
132+
while (1) {
133+
first_char = *name;
134+
fc = first_char;
135+
if (!fc)
136+
return trie->index;
137+
if (!trie->next[fc])
138+
return 0;
139+
trie = &FUNC_TRIES[trie->next[fc]];
140+
name = name + 1;
141+
}
130142
}
131143

132144
/* options */

0 commit comments

Comments
 (0)