C 代码段错误(核心转储)

标签 c gcc segmentation-fault coredump

我尝试注释掉代码并检查它在哪里给我带来了段错误,但找不到它。我什至无法安装 gcc 调试器来检查。请帮忙!

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

FILE *file;
char *registers[] = {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7"};
char *regInBinary[] = {"000", "001", "010", "011", "100", "101", "110", "111"};
char delimiters[4] = " ,\n";
char binaryInstruction[17];

void convertToBinary(char *line);
void binaryToHex();

// Converting each line of source file into 16 bit binary
void convertToBinary(char *line){
    int count = 0;

    char *token = strtok(line, delimiters);
    while(token != NULL){
        // Opcodes
        if(strcmp(token, "add") == 0)
            strcpy(binaryInstruction, "0001");
        if(strcmp(token, "and") == 0)
            strcpy(binaryInstruction, "0101");
      //  if(strcmp(token, "halt") == 0)
      //      main();


        int i;
        for(i = 0; i < 8; i++){ // appends registers in binary
            if(strcmp(token, registers[i]) == 0){
                strcat(binaryInstruction, regInBinary[i]);
                count++;

                if(count == 2){
                    strcat(binaryInstruction, "000");
                }
             }
        }

        token = strtok(NULL, delimiters);
    }

}

// Converting 16 bit binary into hex
void binaryToHex(){
    char hex[5];
    int i, j;

    for(i = 0; i < 16; i = i + 0){
        for(j = 0; j < 4; j++){
            hex[j] = binaryInstruction[i];
            i++;
        }
        printf("%x", (int)strtol(hex, NULL, 2));
    }
    printf("\n");
}


// Starting program Part1
int main(int argc, char *argv[]) {
    char line[40];

    if(argc != 2)
        printf("Usage: %s source_file\n", argv[0]);
    else
        file = fopen(argv[1], "t1.asm"); // open source file

    while(fgets(line, sizeof(line), file)){
        convertToBinary(line);
        binaryToHex();
    }
    //printf("f025")
    fclose(file);
    return 0;
}

所以这段代码可以在我的 Mac 终端上使用 gcc 完美编译,但当我输入 t1.asm 文件时会抛出段错误。

这是一个 C 程序,用于将 LC3 的 AND、ADD 和 HALT 汇编语言指令翻译为机器代码。

谢谢!

最佳答案

file = fopen(arv[1], "t1.asm");

应该是

file = fopen(argv[1], "r");

关于C 代码段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881296/

相关文章:

c - 带空格的字符串输入

正常崩溃,但不是 GDB?

c - 在 c 中释放 char 指针会导致段错误

c++ - VC++ 与 GCC 预处理器

c - 是否保证 memset 会将结构中的填充位清零?

c - 为什么在写入使用字符串初始化的 "char *s"时会出现段错误,而不是 "char s[]"?

c - 使用 dub2() 将输出重定向到文件 : undefined reference to `dub2'

c - 此代码如何列出文件夹中的所有项目?

c - 前 6 次迭代后出现段错误

c - 使用 libpng 过滤器