简体   繁体   中英

Segmentation Fault: 11 when running C program

To try to display graphics using C, I am trying to take advantage of C's "inline assembly" feature. I get no errors during compilation, but when I try to run the program, I get this error:

Segmentation Fault: 11

Here is my code:

int main(){
asm("movb 0xc,%ah");
asm("movb $1,%al");
asm("movw $5,%cx");
asm("movw $5,%dx");
asm("int $0xc");
return 0;
}

Constructive criticism appreciated, insults not. Thanks!

First, it looks like you're trying to use BIOS interrupts to do the graphics, but the graphics interrupt is int 10h (0x10) , not 0xc, so you want to call int $0x10.

Second, you can't call most BIOS interrupts from within 32-bit or 64-bit Linux or Windows programs, so make sure you're compiling this for DOS. Otherwise, calling the invoke interrupt opcode on a BIOS interrupt will crash your program. And if you run a newer version of Windows, you'll probably still have to run your compiled program inside of an emulator like DOSBox for it to work properly.

Finally, GCC inline assembly has a certain format to it:

   __asm__ __volatile__ ( 
         assembler template 
       : output operands                  /* optional */
       : input operands                   /* optional */
       : list of clobbered registers      /* optional */
       );

So for example:

int main()
{
  /* Set video mode: */
  __asm__ __volatile__ (
    "movb $0x0, %%ah \n\
     movb $0x13, %%al \n\
     int $0x10"
    :
    :
    :"ax"
  );

  /* Draw pixel of color 1 at 5,5: */
  __asm__ __volatile__ (
    "movb $0xC,%%ah \n\
     movb $1, %%al \n\
     movw $5, %%cx \n\
     movw $5, %%dx \n\
     int $0x10"
   :
   :
   :"ax","cx","dx"
  );

  /* Reset video mode: */
  __asm__ __volatile__ (
    "movb $0x0, %%ah \n\
     movb $0x03, %%al \n\
     int $0x10"
    :
    :
    :"ax"
  );

  return 0;
}

But the optional fields are only really useful if you're writing functions in assembly language and want to pass in arguments from your C code.

Also, I don't have DJGPP and a DOS installation handy, so I can't test any of this code to make sure it works with the 32-bit protected mode binaries it generates, but hopefully I've hit the nail close enough on the head that you can handle the rest yourself. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM