gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:39:53 28 4
gpt4 key购买 nike

我尝试注释掉代码并检查它在哪里给我带来了段错误,但找不到它。我什至无法安装 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com