【发布时间】:2014-07-23 01:39:20
【问题描述】:
我必须仅使用一个条件跳转指令在数组中找到最小最大值。
编译并链接下面的两个文件后,我得到一个Segmentation Fault (core dumped),但我不明白为什么会这样。
问题:分段错误的原因是什么?
main.cpp
#include <cstdio>
#include <time.h>
using namespace std;
extern "C" void minmax(int n, int * tab, int * max, int * min);
int main(){
const int rozmiar = 100000;
const int liczba_powtorzen = 10000;
int tab[rozmiar] = {1, 3, 3, -65, 3, 123, 4, 32, 342, 22, 11, 32, 44, 12, 324, 43};
tab[rozmiar-1] = -1000;
int min, max;
min = 99999;
max = -99999;
clock_t start, stop;
start = clock();
for(int i=0; i<liczba_powtorzen; i++){
minmax(rozmiar, tab, &max, &min);
}
printf("min = %d max = %d\n", min, max);
stop = clock();
printf("\n time = %f ( %d cykli)", (stop - start)*1.0/CLOCKS_PER_SEC, (stop - start));
return 0;
}
minmax.asm
global minmax ; required for linker and NASM
section .text ; start of the "CODE segment"
minmax:
push ebp
mov ebp, esp ; set up the EBP
push ecx ; save used registers
push esi
mov ecx, [ebp+8] ; array length n
mov esi, [ebp+12] ; array address
mov eax, [ebp+16] ;max
mov edi, [ebp+20] ; min
lp: add eax, [esi] ; fetch an array element
cmp eax, [esi]
jl max ; max<[esi] ->update max
cmp edi, [esi]
jg min ; min>[esi] ->update min
add esi, 4 ; move to another element
loop lp ; loop over all elements
max:
mov eax, esi
ret
min:
mov edi, esi
ret
pop esi ; restore used registers
pop ecx
pop ebp
ret ; return to caller
【问题讨论】:
-
“我能写成这样”:什么是……?
-
minmax 函数内部是否发生了段错误?您应该能够在 gdb 中运行程序并找出段错误时的堆栈跟踪以及导致段错误的指令。
-
@Spundun
Sth是一个不能正常工作的函数,也不符合只有一个条件跳转的要求。 -
相关:在将
max和min发送到你的asm 函数的深渊之前如何初始化它们?现在是它的 UB。 -
是的,这是个好主意,我会更改代码。