Search code examples
cassemblysegmentation-faultdosdjgpp

Keyboard handler causes segfault (djgpp)


Recently I decided, it would be funny, to code some simple MSDOS game. Needles to say, I need code for handling keyboard events.

This is what I came up with for testing:

int i, c = 0;
for ( i = 0; i < 10; i++ )
{
    asm
    (
        "mov $0x00, %%ah         \n"
        "mov $0x00, %%al         \n"
        "int $0x16               \n"
        //"jnz keydn             \n"
        //"mov $0x00, %%al       \n"
        //"keydn:                \n"
        "movw %%ax, (%0)         \n"
            : "=r"(c)
    );

    printf( "%d\n", c & 0xFF );
}

The code is supposed to wait for keypress, and then print out ASCII value of the character. And everything works as expected unless I press key like backspace or esc - then segmentation fault occurs.

enter image description here

I'm unfamiliar with assembly, but really I can't figure out what may cause this error.

I compile with djgpp, and run executables in DosBox

Everything is based on information provided here:

Thank you in advance! :)


Solution

  • This is certainly broken: movw %%ax, (%0): "=r"(c) It tries to write into memory at address given by operand 0 which is an output operand and as such uninitialized. Also it's not a pointer. You probably want to do something like:

       asm
        (
            "mov $0x00, %%ah         \n"
            "mov $0x00, %%al         \n"
            "int $0x16               \n"
                : "=a"(c)
         );
    

    PS: learn to use a debugger or at least cross-reference the register dump with your code.