Home > Enterprise >  program crash after swapping addresses in x86
program crash after swapping addresses in x86

Time:05-29

I want to create two arrays, therefore I use malloc to allocate dynamic storage.

    mov rdi, 10
    call malloc
    mov dl, [rax]
    mov [rbx], dl ; <- right here is the problem
    call malloc

But my program doesn't actually swap values instead it crashes. rdx is 0 after moving [rax] in dl

registers right before the crash

What am I doing wrong? I didn't find anything in the www

EDIT:

This would be equivalent C code, I think. Have to say that I never really worked with C before.

void create_array(int n) {
    int a[n];
    int b[n];
}

CodePudding user response:

It is not entirely clear what you are trying to accomplish, but I'm guessing that you want to malloc two arrays and then swap their first elements, judging by your pseudo C and the comments.

As people have pointed out in the comments, your rbx is never set to any actual address, so it contains garbage (or 0) at that point. Writing to such a location would result in a crash, because it would point to invalid memory. Let me explain.

mov rdi, 10
call malloc

This is correct (though you could have used edi to save a byte). malloc takes its first and only argument in rdi, and returns in rax a pointer to allocated memory. rax at this point is the only thing pointing to valid memory.

mov dl, [rax]

You are now reading the first byte from that allocated memory into dl. This, too, is valid. What isn't valid is the next instruction.

mov [rbx], dl

As mentioned earlier, it doesn't seem that you ever set rbx to anything. It's pointing to some random, almost certainly invalid place in memory (or to nowhere). What I think you intended to do is something like this.

mov edi, 10
call malloc
mov rbx, rax ; First array in rbx

mov edi, 10
call malloc ; Second array in rax

mov dl, [rax] ; Load byte from second array
mov [rbx], dl ; Store that byte to first array

This example doesn't actually do any swapping (I'll leave that as an exercise for you), but it illustrates that rbx should point to valid memory before anything may be written to (or read from) the memory location it contains.

  • Related