c - 段错误: 11 when running C program

标签 c segmentation-fault int inline-assembly

为了尝试使用 C 显示图形,我尝试利用 C 的“内联汇编”功能。我在编译期间没有收到任何错误,但是当我尝试运行该程序时,出现此错误:

段错误:11

这是我的代码:

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

赞赏建设性批评,不接受侮辱。 谢谢!

最佳答案

首先,看起来您正在尝试使用 BIOS 中断来处理图形,但图形中断是 int 10h (0x10) ,而不是 0xc,所以你想调用 int $0x10。

其次,您无法从 32 位或 64 位 Linux 或 Windows 程序中调用大多数 BIOS 中断,因此请确保您正在为 DOS 编译此中断。否则,在 BIOS 中断上调用调用中断操作码将使您的程序崩溃。如果您运行较新版本的 Windows,您可能仍然需要在 DOSBox 等模拟器中运行编译后的程序才能正常工作。

最后,GCC 内联汇编有一定的格式:

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

例如:

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;
}

但是,只有当您使用汇编语言编写函数并希望从 C 代码传递参数时,可选字段才真正有用。

此外,我手边没有 DJGPP 和 DOS 安装,因此我无法测试任何代码以确保它可以与它生成的 32 位保护模式二进制文件一起使用,但希望我已经达到了将头部钉得足够紧,以便您可以自己处理其余部分。祝你好运!

关于c - 段错误: 11 when running C program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7068147/

相关文章:

c - 在 C 中使用 block

c - C 中的 setgid() 调用不起作用

c++ - 某些 lua/c++ 代码中的 SIGSEGV 错误

iphone - 将 NSString 转换为整数

c - 如何将 char 赋值给 int 值?

Java,scan double只接受int

c++ - Totalview:有没有办法硬编码断点?

c - C语言中如何判断一个字符串是否为整数?

c - 堆栈字符串上 strtok_r 中的段错误

c++ - 段错误: 11 c++ when using vector