Skip to content
Advertisement

How to write a swap function in assembly?

I’ve been trying to figure out how to write a x86 GAS swap function for my program. I know its easier to do xchg or just write it C, but I want to be able to write it out anyways.

On my 1st midterm we were given this as as swap function:

movl 8(%ebp), %edx
movl 12(%ebp), %ecx
movl (%edx), %ebx
movl (%ecx), %eax
movl %eax, (%edx)
movl %ebx, (%ecx)

but I receive a segmentation fault when running this. Haven’t been able to succeed in finding my answer anywhere else on the web, so much help would be appreciated.

EDIT:

C CODE:

void program2()
{
int numA[2] = {5,10};
int *num1 = &numA[0];
int *num2 = &numA[1];
int loop=0;
printf("stop3n");
for(loop=0;loop<=10;loop++)
{
    *num1 *=2;
    *num2 *=3;
    printf("%dn%dn",*num1,*num2);
    _asSwap(*num1,*num2);
    printf("stop5n");
    printf("P2num1= %dn P2num2= %dn",*num1,*num2);

}

Assembly:

_asSwap:
push    %ebp
movl    %esp, %ebp

movl 8(%ebp), %edx
movl 12(%ebp), %ecx
movl (%edx), %ebx
movl (%ecx), %eax
movl %eax, (%edx)
movl %ebx, (%ecx)

pop %ebp
ret

Advertisement

Answer

You passed the values, not the pointers. If you’d included the prototype in your C, the compiler would have caught that (instead of warning about an un-declared function, and assuming it took int parameters).

extern int _asSwap(int *a, int *b);

A debugger would also have caught this, if you checked the address that segfaulted.

Also, it’s not normal to prefix your C function names with _. OS X prefixes _ onto C symbol names, and so did Linux a.out (now replaced by ELF). So you in some cases need a leading _ in the asm, but don’t use it in C.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement