首页 > 解决方案 > “分段错误(核心转储)”汇编和c链接程序

问题描述

########
# int mycompare( int size, int x[], int y[] )
#
.text
.global mycompare

mycompare:
    pushl %ebp
    movl %esp, %ebp
    subl $4 , %esp
    movl $0 , -4(%ebp)

    movl 12(%ebp), %edx # int x[]
    movl 16(%ebp), %ebx # int y[]
    mov $0, %ecx
ciclo:
    cmp 8(%ebp) , %ecx
    je fim

    mov (%edx,%ecx,4), %eax
    cmp (%ebx,%ecx,4), %eax
    jne fim_wrong
    inc %ecx
    jmp ciclo

fim_wrong:
    mov %ecx, %eax

    mov %ebp, %esp
    pop %ebp
    ret

fim:
    mov $0xFFFFFFFF, %eax

    mov %ebp, %esp
    pop %ebp
    ret

和 c Main


#include <stdio.h>
#include <stdlib.h>

#define MAX 1024
#define MAXLINE 2048

extern int mycompare( int size, int x[], int y[] );


int readOneArr(int max, int a[]) {
    char line[MAXLINE];
    if (fgets(line, MAXLINE, stdin) == NULL) exit(1);
    int i=0;
    char *curr;
    char *new=line;
    do {
        curr=new;
        a[i] = strtol(curr, &new, 10);
        i++;
    } while (i<max && curr!=new);
    return i-1;
}

int readArrs(int max, int a[], int b[]) {
    int na = readOneArr( max, a );
    int nb = readOneArr( max, b );
    if (na!=nb) return -1;
    return na;
}

int main() {
    int i, n;
    int a1[MAX], a2[MAX];

    n = readArrs(MAX, a1, a2);
    if(n == -1) {
        fprintf(stderr,"wrong input!\n");
        return 1;
    }
    i=mycompare(n, a1, a2);
    if ( i == -1 )
        printf("equal\n");
    else
        printf("different at %d\n", i);
    return 0;
}


我使用以下 cc 设置进行编译

cc -m32 -Wall -std=c11 -o main.c func.s

它是一个比较两个整数数组的程序,返回它们不同的第一个索引,如果数组相等,则返回-1。数组具有相同的大小,并且该大小也是函数的参数。

它给了我:

Segmentation fault (core dumped)

例如,如果我尝试输入:

1 2 4 7 10 
1 2 4 7 10 

标签: cassemblyx86calling-convention

解决方案


推荐阅读