简体   繁体   中英

Segmentation fault when passing arrays from C to nasm

I have a C program which calls a function that is implemented in nasm. The C-call:

    extern void calc(float *, float *, float *, float *);
    //...
    float *data1, *data2, *results1, *results2;
    data1 = (float *)malloc(MAXLINES * sizeof(float));
    //...
    calc(data1, data2, results1, results2);
    /...
    for(i=0;i<linesread;i++) {
        printf ("Zeile %u: result1 = %f,\tresult2 = %f\n", i, results1[i], results2[i]); //Segmentation fault
    }

nasm:

segment .data

constAir:   dq 1.11330e-10
constOil:   dq 2.33656e-10
pi:     dq 3.1415
four:       dq 4

SEGMENT .text

GLOBAL calc

calc:

PUSH EBP
PUSH EAX
PUSH EBX
PUSH ECX
PUSH EDX
MOV EBP, ESP
ADD EBP, 20
MOV EAX, [EBP]      ; data1
MOV EBX, [EBP + 4]  ; data2
MOV ECX, [EBP + 8]  ; results1
MOV EDX, [EBP + 12] ; results2

; results1/2 = data1 / (4 * PI * constAir/Oil * data2 * data2)

FLD QWORD [four]
FMUL QWORD [pi]
FMUL QWORD [constAir]
FMUL QWORD [EBX]
FMUL QWORD [EBX]
FST ST1
FLD QWORD [EAX]
FDIV ST1
FST QWORD [ECX]

FLD QWORD [four]
FMUL QWORD [pi]
FMUL QWORD [constOil]
FMUL QWORD [EBX]
FMUL QWORD [EBX]
FST ST1
FLD QWORD [EAX]
FDIV ST1
FST QWORD [EDX]

POP EDX
POP ECX
POP EBX
POP EAX
POP EBP
RET

I get a segmentation fault in the printf function in the C-code. It seems to me that somehow the arrays are not filled after calling the nasm procedure.

Best regards and have a nice weekend!

You forgot about the return address being stored on the stack.

Current code:

MOV EAX, [EBP]      ; data1
MOV EBX, [EBP + 4]  ; data2
MOV ECX, [EBP + 8]  ; results1
MOV EDX, [EBP + 12] ; results2

Corrected code:

MOV EAX, [EBP + 4]  ; data1
MOV EBX, [EBP + 8]  ; data2
MOV ECX, [EBP + 12] ; results1
MOV EDX, [EBP + 16] ; results2

Also, you are using floats, which are probably 32 bits on your architecture, but you are using QWORD (64 bits) to manipulate them. And declaring four as 4 instead of 4.0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM