Favolas
Favolas

Reputation: 7243

MIPS return value from memory address

I have to program in Assembly (MIPS) a function to return the max value of an array.

The C code is this:

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

int MaxAssembly(int *ptr, int num_elements); 

int main ( ) 
{ 
  int n=9; 
  int tab[] = {2, -8, 0, 25, 14, 2, 9, 15, -32}; 
  printf("The maximum is %d \n", MaxAssembly(tab,n)); 

MaxAssemblyis the function I have to program in Assembly.

I'm not in the part to find the max. My problem in in reading the functions arguments. I have made this code to do some tests.

    .data

    .text
    .globl  MaxAssembly

MaxAssembly:
    add $9,$5,$zero
    move    $2,$9
    jr  $ra

Doing this code I can see that I'm reading the second function argument as expected. It's printed on the screen The maximum is 9 Changing the code to:

    .data

    .text
    .globl  MaxAssembly

MaxAssembly:
    move    $2,$4
    jr  $ra

I can see that it's reading the first argument of the function as a memory address and it's printed on the screen The maximum is 2143429780. So far is working as expected.

The problem is when I try to read the element stored at that memory address (the first element of the array). I'm getting one segmentation fault... I'm doing this:

    .data

    .text
    .globl  MaxAssembly

MaxAssembly:
    lw      $16,0($4)
    move    $2,$16
    jr  $ra

What am I doing wrong? wasn't lwsupposed to store at $16 the first item of the array? Using lbis the same

Upvotes: 3

Views: 11847

Answers (1)

Wiz
Wiz

Reputation: 2143

Yes, lw $s0, 0($a0) will read a full word from the address in $a0 to $s0. Unlike, lb, memory access via lw must use word-aligned addresses (i.e., two LSB are zero). I suspect that's where the problem occur.

Upvotes: 2

Related Questions