as2d3
as2d3

Reputation: 905

GAS Assembly program segmentation fault (writing to auto variable)

I intend to do this in C:

#include<stdio.h>
int main() {
  int arr[5];
  arr[0] = 5;
  arr[1] = 0;
  arr[2] = 1;
  arr[3] = 3;
  arr[4] = 4;
  int max = 0;
  for(int i = 0;i < 5;i++)
    if(max < arr[i])
      max = arr[i];
  printf("%d\n", max);
  return 0;
}

This is my code link: array_max.s. This is my assembly code in AT&T format :

.data

.text
.globl _start
_start:
  movl $5, -20(%ebp)
  movl $0, -16(%ebp)
  movl $1, -12(%ebp)
  movl $3, -8(%ebp)
  movl $4, -4(%ebp)
  movl $0, %ecx
  movl $5, %eax
  loop:
    cmp $0, %eax
    je terminate
    cmp %ecx, -20(%ebp,%eax,4)
    jg assign
    jmp loop


terminate:
  movl $4, %eax
  movl $1, %ebx
  movl $1, %edx
  int $0x80
  movl $1, %eax
  int $0x80
  ret

assign:
  movl -20(%ebp,%eax,4), %ecx
  ret

I am having a segmentation fault on the very first instruction movl $5, -20(%ebp). I am new to this, please help.

Upvotes: 3

Views: 261

Answers (1)

jfMR
jfMR

Reputation: 24768

I am having a segmentation fault on the very first instruction movl $5, -20(%ebp).

You are not allocating any space on the stack for arr (i.e.: int arr[5]):

pushl %ebp
movl %esp, %ebp
subl $20,%esp //<--- memory allocation

In order to deallocate the memory allocated on the stack by restoring the previous stack frame, use the leave instruction just before ret.

Upvotes: 5

Related Questions