2

我写了一个实现归并排序算法的 MIPS 子程序(代码在文章的最后)。它接收指向数组的指针及其大小。排序,不要返回任何东西。

我一直在调试它,修复了一些错误,并且由于子例程在达到基本情况(大小为 1 的数组)之前似乎运行良好,现在我正在使用 gdb 和这段 C 代码来针对特定情况对其进行调试:

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

extern void merge_sort(char*, int);

int main(int argc,char **argv){

    char* vector;
    vector = (char*)malloc(sizeof(char));
    if(vector == NULL) printf("error");

    size_t vector_size = 1;
    memcpy(vector,"5",vector_size);

    merge_sort(vector, vector_size);

    int i;
    for(i = 0; i < vector_size; i++){
            printf("%c ", vector[i]);
    }

    printf("\n");
    return 0;
}

我的问题是,当我单步执行子程序行时,当我到达倒数第二行(jr ra)时,它崩溃并以代码 060 退出,并且 gdb 显示此消息:

Warning: GDB can't find the start of the function at 0x400730.
    GDB is unable to find the start of the function at 0x400730
    and thus can't determine the size of that function's stack 
    frame. This means that GDB may be unable to access that stack
    frame, or the frames below it.

    This problem is most likely caused by an invalid program 
    counter or stack pointer.  However, if you think GDB should
    simply search farther back from 0x400730 for code which looks
    like the beginning of a function, you can increase the range 
    of the search using the `set heuristic-fence-post' command. 
0x004008a0 in _start

我不明白为什么会这样。我认为这可能是存储在 中的地址有问题,ra堆栈分配错误,或者 C 和 MIPS 代码之间的链接错误,但我不知道我做错了什么。

下面是 merge_sort 的 MIPS 代码:
对于基本情况,代码运行到 行beq t1, zero, SALIDA,然后跳转到SALIDA,并结束。所以我只是粘贴那部分代码(SALIDA 意味着退出西班牙语:P)。

#include <mips/regdef.h>
#include <sys/syscall.h>

#define     SSIZE   (56)
#define     O_RA    (48)
#define     O_FP    (44)
#define     O_GP    (40)
#define     O_S3    (36)
#define     O_S2    (32)
#define     O_S1    (28)
#define     O_S0    (24)
#define     O_ARG0  (SSIZE)
#define     O_ARG1  ((SSIZE) + 4)

.text
.align  2
.globl  merge_sort
.ent    merge_sort

merge_sort:
.frame $fp, SSIZE, ra
.set noreorder
.cpload t9
.set reorder     

subu    sp,sp,SSIZE

sw  s0, O_S0(sp)
sw  s1, O_S1(sp)
sw  s2, O_S2(sp)
sw  s3, O_S3(sp)

sw  gp, O_GP(sp)
sw  $fp, O_FP(sp)
sw  ra, O_RA(sp) 
move    $fp, sp

sw  a0, O_ARG0($fp)
sw  a1, O_ARG1($fp)

lw  t0, O_ARG1($fp)
addi    t1, t0, -1

beq     t1, zero, SALIDA

SALIDA:     
lw  s0, O_S0($fp)
lw  s1, O_S1($fp)
lw  s2, O_S2($fp)
lw  s3, O_S3($fp)

move    sp, $fp
lw  gp, O_GP($fp)
lw  $fp, O_FP($fp)
lw  ra, O_RA($fp) 

addiu   sp, sp, SSIZE

jr  ra

.end    merge_sort
4

1 回答 1

3

我认为您的问题是在子例程接近尾声时出现以下问题:

lw  $fp, O_FP($fp)    // restores $fp
lw  ra, O_RA($fp)     // restore ra, but $fp isn't pointing to our frame anymore

我认为如果你颠倒这些指令可能会更好。

于 2012-05-02T01:03:57.613 回答